April 9, 2020
Estimated Post Reading Time ~

Registering a Servlet for every Page in AEM

UseCase: I had a situation in which needed to return custom information corresponding to every page in AEM and also use it via component to display to end-user.
  • Then I have to invoke a Servlet on every page and with the use of the selector want to return some information in JSON format which can be used to display via Component on a Page to end-user.
Solution: For such situations, we use the resourceType as cq/Page for registering Servlet, so that Servlet is registered for every Page.
  • Then with the use of a particular selector, we can get results like list information/required custom information for every AEM page and display either via component with its ajax request has a url of Current Page. Selector which invokes the Servlet and renders result.
Note: Just for reference Sling resolves on basis of Primary Type example cq:Page for Page and dam:Asset for Dam in case sling:resourceType is missing.
Code Snippet:

@Component(name = "Site-Results", metatype = false, configurationFactory = false, policy = ConfigurationPolicy.OPTIONAL)

@Service(Servlet.class)

@Properties([
    @Property(name = "sling.servlet.resourceTypes", value = ["cq/Page"]),
    @Property(name = "sling.servlet.selectors", value = "results"),
    @Property(name = "sling.servlet.extensions", value = ["json"]),
    @Property(name = "sling.servlet.methods", value = "GET"),
    @Property(name = "sling.servlet.description", value = "Gives Results for Every Page")
])

class ResultsServlet extends SlingSafeMethodsServlet {
    protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) {

//Implement Your Logic
}
}


By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.