Reading a page property inside Sling servlet doGet()
Hi,
I am new to AEM development.
I have a sling servlet with the below code and I am trying to read a page property. This code snippet works in Author mode, but not in the publisher.
ResourceResolver resourceResolver = request.getResourceResolver();
PageManager pageManager = resourceResolver.adaptTo(PageManager.class);
String currentpagePath = new URI(request.getHeader("referer")).getPath();
Page page = pageManager.getPage(currentpagePath.substring(0, currentpagePath.lastIndexOf(".")));
ValueMap pageProperties = page.getProperties();
excludeBefore = pageProperties.get("opendayEventDate", String.class);
LOG.info(ERROR_MSG_PREFIX + "page property exclude before "+ excludeBefore);
Did a bit of debugging, and it seems the page path comes in different structure when the code runs in publisher. Can someone please advise how to make it work in both Publisher and Author? Can you please suggest the best practice here?
I ve tried the below code and it does not seem to work either (reason being the resource object is null):
// try with resources block to manage resource resolver life cycle
try (ResourceResolver serviceRes = resourceResolverFactory.getServiceResourceResolver(authenticationInfo)) {
PageManager pm = serviceRes.adaptTo(PageManager.class);
Resource resource = request.getResource();
Page containingPage = pm.getContainingPage(resource);
ValueMap pageProperties = containingPage.getProperties();
excludeBefore = pageProperties.get("opendayEventDate", String.class);
LOG.info(ERROR_MSG_PREFIX + "page property exclude before "+ excludeBefore);
} catch (LoginException e) {
LOG.error(ERROR_MSG_PREFIX + "Login Exception occurred " + e.getMessage());
}