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 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 :
[java]
@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
}
}
[/java]
Hey Suresh , It will be cq/Page as mentioned in the blog .
Suppose you have a usecase when you want to invoke servlet for all pages and then you want to show information according to selectors or your custom need via ajax call , then you can use this concept .
Hi Bro,
How it can be used on every page.Please correct me if I am wrong.It should be accessed via sling:resourceType(==cq/Page) property right.can u explain more?
it should be cq:Page instead cq/Page I think.Correct me if I am wrong.