8

I wanted to know if there is a way to get the rendered HTML output of a Page node in CQ5 without hitting the actual url. I have the Page node and I want to get the rendered HTML output of that Page node programmatically in java and store it in a string without hitting the page URL.

Any help is appreciated, thanks in advance!

Rakesh
  • 4,264
  • 4
  • 32
  • 58

2 Answers2

6

Node itself it's just a data. Sling framework responsible for rendering this data. It use a bunch of rules to determine how this data should be rendered.Sling Script Resolution Cheet Sheet As Sling is web framework it renders data via http requests.

To emulate this request in CQ/AEM I suggest to use com.day.cq.contentsync.handler.util.RequestResponseFactory service

import org.apache.sling.engine.SlingRequestProcessor;
import com.day.cq.contentsync.handler.util.RequestResponseFactory;

@Reference
private RequestResponseFactory requestResponseFactory;

@Reference
private SlingRequestProcessor requestProcessor;

public String doStuff(){
    HttpServletRequest request = requestResponseFactory.createRequest("GET", "/path/to/your/node.html");
    request.setAttribute(WCMMode.REQUEST_ATTRIBUTE_NAME, WCMMode.DISABLED);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    HttpServletResponse response = requestResponseFactory.createResponse(out);

    requestProcessor.processRequest(request, response, resourceResolver);        
    return out.toString(response.getCharacterEncoding());
}

Hope it helps.

Dzianis Sudas
  • 364
  • 3
  • 16
2

You can access node by providing a correct view. As you need rendered html view, use .html with your node to get rendered html. So your node path will be

/content/path/to/page/jcr:content/par/node_name.html

Now to read html programmatically, you can make an http request to above path from your path, and save response as string.

Mohit Bansal
  • 384
  • 3
  • 12
  • Thanks! I will try this. – Rakesh Sep 23 '15 at 06:04
  • Please explain what you have done, because concept wise this approach should work for your usecase. – Mohit Bansal Oct 16 '15 at 07:46
  • I have a page node which has several chhild nodes of different resourceType and I wanted the html output of the page node exactly the same way as rendered by the browser, your approach works only for a single node and not for all the child nodes. – Rakesh Oct 16 '15 at 08:54
  • In this case, you should have a par node below your page node. Your data selector should include path of par. ie "/content/path/to/page/jcr:content/par.html" and it will return html of all component dropped in par – Mohit Bansal Oct 17 '15 at 09:02