Search code examples
aemjcrsling

Get html output from a jcr node in CQ5


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!


Solution

  • 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.