What is Servlet in AEM ? | Types of Servlet | Create Servlet in AEM

Hello Developer’s, In this article we’ll learn What is Servlet in AEM ? , Types of servlet and how we can create servlet in AEM. So if you ever work with Spring boot then you are very familiar with servlet. But in AEM case servlet are little different in execution.

What is Servlet in AEM ?

So Servlet is a piece of java code which is running on a server, only difference in core java and servlet is; core java always starts with a main method while a servlet triggered when request sending by the client and it gives response.

A Servlet is a class which used to extend capabilities of servers. It means host applications accessed by a request and response programming models.

How servlet actually work in AEM ?

Let’s take the above diagram for better understanding.

So when we design/writes any servlet then it is firstly registered as an OSGI service and OSGI instantiate/initialized the servlet and get ready them for the Sling framework. Thus, when we request as a client by path/url then it goes OSGI first then the job of the Sling framework is to choose the specific servlet by taking reference of “sling.servlet.paths” or “sling.servlet.resourceTypes” and then Servlet Container is execute the servlet and closed it. So we can say that Servlet Container job is to actual execute the servlet and destroy it. As we have servlet a, b and c in different packages

More topics related AEM

Types of Servlet in AEM | How can we Create It ?

Basically servlets are registered by two types:

  • Servlet By Path Type
  • Servlet By Resource Type

1) By Path Type

In this type of servlet we registered our servlet by using path and when the specified path hit then the servlet is called and executed.

Path type of servlet is not recommended way to create servlet as adobe but in some case we need to create by path only.

Code:
package com.adobe.aem.guides.wknd.core.servlets;

import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;

import org.apache.sling.api.servlets.SlingAllMethodsServlet;

import org.apache.sling.servlets.annotations.SlingServletPaths;

import org.osgi.service.component.annotations.Component;


import javax.servlet.Servlet;
import javax.servlet.ServletException;
import java.io.IOException;

@Component(service = Servlet.class)
@SlingServletPaths(value = { "/bin/pages", "/custom/pages" })
public class MyPathTypeServlet extends SlingAllMethodsServlet {

    @Override
    protected void doGet(final SlingHttpServletRequest req, final SlingHttpServletResponse resp)
            throws ServletException, IOException {
        resp.getWriter().write("path type servlet");
        
         // write your codes..........................................

    }
}

Let’s Understand code:

@Component defines that this a OSGI service and have type Servlet, This means we registered this servlet as OSGI.

@SlingServletPaths It defines the sling framework that, it is a path type servlet and it can be access and execute by paths, as we have defined two paths /bin/pages and /custom/pages.

aem servlet

but here /bin is by default present in Script Resolver and if we need to add new path then we need to add it in http://localhost:4502/system/console/configMgr by searching script resolver and add new path as above we have added in image.

The url which triggered this servlet will be as : http://localhost:4502/bin/pages/ or http://localhost:4502/custom/pages/

Note: Class should be extend with SlingAllMethodsServlet or SlingSafeMethodsServlet, if servlet have only get method then SlingSafeMethodsServlet can be used otherwise we need to use SlingAllMethodsServlet in both type of servlets.

Now we can write methods (doGet / doPost) and by the help of req we can handle requests and by the help of resp we can send responses.

2) By Resource Type

In this type of servlet we registered our servlet by using sling resource type and when the specified resource called then the servlet is called and executed. But here in resource type we can add selectors and extensions. Thus to triggered the servlet we need resource, selectors and extensions.

Code:

package com.adobe.aem.guides.wknd.core.servlets;

import com.day.cq.commons.jcr.JcrConstants;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
// import org.apache.sling.api.request.RequestParameter;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.servlets.HttpConstants;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
// import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.apache.sling.servlets.annotations.SlingServletResourceTypes;
import org.osgi.service.component.annotations.Component;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import java.io.IOException;
// import java.util.List;

@Component(service = Servlet.class)
@SlingServletResourceTypes(resourceTypes = "wknd/components/page", selectors = "myservlet", extensions = "xml", methods = HttpConstants.METHOD_GET)
public class MyResourceTypeServlet extends SlingAllMethodsServlet {


    /*
     * (non-Javadoc)
     * 
     * @see
     * org.apache.sling.api.servlets.SlingSafeMethodsServlet#doGet(org.apache.sling.
     * api.SlingHttpServletRequest, org.apache.sling.api.SlingHttpServletResponse)
     */
    @Override
    protected void doGet(final SlingHttpServletRequest req,
            final SlingHttpServletResponse resp) throws ServletException, IOException {

        final Resource resource = req.getResource();
        resp.setContentType("text/plain");
        resp.getWriter().write("resource type servlet");

        // write your codes..........................................

    }

}

Let’s Understand the Code:

All other codes are working same as path type so you can refer the code explanation of path type. But here in line number 20 we can can see that something changed, so this is what we declared this servlet as sling resource type, and we have given a resource(to check this resource please see the below picture) and then gives selector (myservlet), this defines selector and when we hit servlet then we need selector and extension also.

resource type servlet in aem

The url which triggered this servlet will be as : http://localhost:4502/content/wknd/us/en/_jcr_content.myservlet.xml

You can create override doPost method but remember to add in sling (line number 20) HttpConstants.METHOD_POST to handle post requests. You can use {} for multi selector, extensions or methods type. Refer below code;

        methods = {HttpConstants.METHOD_GET,HttpConstants.METHOD_POST},

        selectors = {"myservlet","mynewservlet"},
        extensions = {"txt","xml"}

Have any query ?

feel free to comment now, happy to help. Thankyou

Leave a Comment