aem

Retrieving Page Properties into Sling Servlet using resource resolver


I've created a page with properties like jcr:title, siteName, storeCode, canonicalUrl, and more. Within a Java Sling Servlet handling this page, I need to retrieve all properties of the current page, specifically storeCode, to access data from different language versions of the site. Can this be achieved without relying on global objects?

I have tried using a Sling Model(using the global object or @ScriptVariable), but now I need to achieve this through a Sling servlet request.


Solution

  • You can achieve this using a resource resolver. Because the request originates from the current page, we can retrieve the resource of the current page as you mentioned. The ValueMap interface of the resource provides access to all the properties of the resource. However, ensure you handle potential null pointer exceptions. Certain properties might not always be present, so proper handling prevents code failures.

    Below is a sample code snippet

    @Component(service = Servlet.class)
    @SlingServletPaths(value = "/bin/pageProps")
    @HttpMethodConstraint(value = HttpConstants.METHOD_GET)
    public class PageProperties extends SlingSafeMethodsServlet {
        @Override
        protected void doGet(@NotNull SlingHttpServletRequest request, @NotNull SlingHttpServletResponse response) throws ServletException, IOException {
            // Obtain the ResourceResolver from the request object.
            ResourceResolver resourceResolver = request.getResourceResolver();
            //Get the PageManager by adapting resourceResolver to PageManager
            PageManager pageManager = resourceResolver.adaptTo(PageManager.class);
            //Retrieve the Page by specifying the path from which you'd like to obtain its properties
            Page page = pageManager.getPage("/content/wknd/us/en/firstPage");
    
            if (page != null) {
                // Get the page properties
                ValueMap properties = page.getProperties();
                JsonObjectBuilder objectBuilder = Json.createObjectBuilder();
    
                // Now you can access individual properties as below
                String title = properties.get("jcr:title", String.class);
                String description = properties.get("jcr:description", String.class);
    
                objectBuilder.add("title", title);
                objectBuilder.add("description", description);
                response.getWriter().write(objectBuilder.build().toString());
            } else {
                response.getWriter().write("Page not found");
            }
        }
    }
    

    This code retrieves the title and description of the current page and builds a JSON object containing this information. When the specified servlet path is accessed (likely through a GET request), the servlet responds with the generated JSON object.