Get the rendered HTML for an AEM resource, component or page

Adobe Experience Manager | AEM/CQ | Apache Sling

Get the rendered HTML for an AEM resource, component or page

It's easy to retrieve a rendered component by making a GET request. Apache Sling's SlingMainServlet and DefaultGetServlet will process GET requests, take the path's extension into account, and return the rendered resource. The most obvious example of triggering this process is simply typing the component's path into the browser's address bar or making an AJAX call. You can retrieve the HTML markup (or JSON, XML, txt, PDF, etc...) for a component as well as a page if you provide the correct path. After all, they're both just Sling resources.

Trying to get the rendered HTML of a component on the server side is still easy, but requires a little more work. Without knowing the inner workings of Sling, you might use Java's java.net.HttpUrlConnection class to construct and make an HTTP request from within your application to your application.

The better way is to use the SlingRequestProcessor service as the entry point into Sling's process. The processRequest method of the SlingRequestProcessor takes an HttpServletRequest, HttpServletResponse, and Resource Resolver as parameters. The only trick is that you need to provide a request that enables you to set the request path and a response that enables you to get the OutputStream as a String.

AEM provides the RequestResponseFactory where you can easily get such a request and response.



You'll need to provide your own mock request and response in Apache Sling. Fortunately, it already exists. You need the HttpRequest, HttpResponse, and TestServletOutputStream classes.



You will need to include the  org.apache.sling.engine dependency in your pom file. If your bundle resolves but your component remains unsatisfied, make sure sure you've included the package in the Import-Package section of your maven-bundle-plugin.