Sunday 23 November 2014

Introduction to Sling Servlets in AEM

Hi All

This blog intended to the beginners of CQ5 to understand what are the sling servlet and how to create a very basic servlet. We can create the servlet in AEM by two ways :

1) By using Sling-specific @SlingServlet annotation.
2) By using  generic maven-scr-plugin annotations.



Here Below i'll show you an example how to resolve the servlet as per the resourceTypes.

Step 1 : Create a component /apps/AEMProject/components/content/servletchecker.
Step 2 : Inside servletchecker.jsp Add the below code.

 <form name="form" method="post" action="<c:out value="${resource.path}" />">   
   <input type="submit" />   
  </form>   

Here resource.path refer to the content node, that might all aware :)
Step 3 : Create the servlet as follows :
 @Component   
  @Service(Servlet.class)   
  @Properties({   
    @Property(name = "sling.servlet.resourceTypes" , value = "AEMProject/components/content/servletchecker" ),   
    @Property(name = "sling.servlet.methods" , value = "POST" )   
  })   
  public class ConfigurationChecker extends SlingAllMethodsServlet {   
    private static final long serialVersionUID = -7945683216509362012L;   
    private final static Logger logger = LoggerFactory.getLogger(ConfigurationChecker.class);   
     @Override   
     protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {   
           response.setContentType("text/plain");   
           logger.info("Success");   
     }   
  }   

Here as you can see action is resource.path, in my case it is /content/AEMProject/English/test/jcr:content/par/servletchecker
At this node Sling will look for AEMProject/components/content/servletchecker resource as we registered in our servlet, If it gets resolve then the servlet execute.

Also one can use the selectors to resolve in that case your jsp would be like :
 <form name="frm" method="post" action="<c:out value="${resource.path}" />.email">  
   <input type="submit" />  
 </form>  


And add the property on your servlet :
@Property(name = "sling.servlet.selectors" , value = "email")

Below would be the code :


 @Override  
        protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {  
                   response.setContentType("text/plain");  
                   String selectors[] = request.getRequestPathInfo().getSelectors();  
                   logger.info("Resource is "+resourceType);  
                   for(int i=0 ; i<selectors.length ; i++)  
                   {  
                        String selector = selectors[i];  
                        if(selector.equals("email"))  
                        {  
                             logger.info("Work with Email");  
                        }  
                   }  
                   logger.info("Success");  
        }  

Thanks



1 comment: