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