Blogs > Servlets in AEM
AEM Sites
Servlets in AEM
| Feburary 1, 2023Happy to see you. Welcome to a new blog.
Servlets in AEM
In this blog we will be understanding what are servlets in AEM plus what are the ways in which they are registered. Also we will understand in brief which type to use and when. Lets begin!
What are Servlets
Servlets are java classes which are meant to handle HTTP requests and their respective responses also allowing the developer to generate dynamic content. They provide variety of methods like doGET, doPOST, doPUT, doOPTIONS and doHEAD.
doGET - Handles HTTP GET requests, typically used to retrieve data from the server. It is used to serve resources and render data without altering the server's state.
doPOST - Handles HTTP POST requests, used for submitting data to the server to create or modify resources. It is generally used for form submissions, API requests, or sending data that may change the server state.
doPUT - Handles HTTP PUT requests, which are used to update an existing resource or create a new one if it doesn’t exist.
doOPTIONS - Handles HTTP OPTIONS requests, used by clients to discover what HTTP methods are supported by the server for a given resource. It is generally used for handeling CORS(Cross Origin Resource Sharing) and checking server's capability.
doHEAD - Handles HTTP HEAD requests, which are similar to GET but do not return the body of the response, only headers.
Registering a Servlet
There are tow ways in which a servlet is actually registered in aem
-
By Path
Whenever we have to test the reponse or functioning of the servlet prior, it is preferred to register it by path. Also whenever any custom endpoint is created in the aem environment, they generally are not tied to any sort of aem resource, like components. In such case too, the servlet is preferred to be registered by path. An example is creating an endpoint from content fragments.
-
By Resource Type
Now when a servlet is supposed to act on a specific resource or is supposed to work within the context of a specific resource or perform logic specifically related to the content or inputs recieved from the page, at this moment we are ought to register the servlet by resource type.
Registering by Path
-
In order to register a servlet by path, you need to add the following snippet to it. Remember the path must begin with /bin.
@Component( service = Servlet.class, property = { "sling.servlet.paths=/bin/asset", "sling.servlet.methods=GET", "sling.servlet.extension=json" } )
-
Here we have created a servlet that reads the metadata properties of an asset.
package com.local.core.servlets; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.servlets.SlingSafeMethodsServlet; import org.osgi.service.component.annotations.Component; import javax.jcr.Node; import javax.jcr.Property; import javax.jcr.PropertyIterator; import javax.naming.spi.Resolver; import javax.servlet.Servlet; import javax.servlet.ServletException; import java.io.IOException; import java.io.PrintWriter; import java.util.Properties; @Component( service = Servlet.class, property = { "sling.servlet.paths=/bin/asset", "sling.servlet.methods=GET", "sling.servlet.extension=json" } ) public class AssetPathServlet extends SlingSafeMethodsServlet { @Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println("Get Invoked"); try(ResourceResolver resolver = request.getResourceResolver()){ Resource resource = resolver.getResource("/content/dam/Sample/sun.jpg"); Node asset = resource.adaptTo(Node.class); Node metadata = asset.getNode("jcr:content").getNode("metadata"); out.println(metadata.getName()); PropertyIterator allProperties = metadata.getProperties(); if(allProperties.hasNext()){ while(allProperties.hasNext()){ Property property = allProperties.nextProperty(); out.println(property.getName()); } } }catch (Exception e){ e.printStackTrace(); } } }
-
Here as you can see the servlet is registered by /bin/assets.json. On hitting the servlet in the postman, we are able to see its response in the console.
Register by Resource
-
In order to register your servlet by a resource type, you need to first create a component and add it on a page. In this case we have added a demo component on a page.
-
You need to add the following snippet to your servlet. The same functionality we will achieve by registering the servlet by resource type.
@Component( service = Servlet.class ) @SlingServletResourceTypes( resourceTypes = "/apps/local-project/components/servletresource", methods = HttpConstants.METHOD_GET )
-
After registering your servlet with resource type, you need to hit it on the postman to recieve its response. The path to the servlet will be the path of the page on which your component is present ending till the location of the component itself.
package com.local.core.servlets; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.servlets.HttpConstants; import org.apache.sling.api.servlets.SlingSafeMethodsServlet; import org.apache.sling.servlets.annotations.SlingServletResourceTypes; import org.osgi.service.component.annotations.Component; import javax.jcr.Node; import javax.jcr.Property; import javax.jcr.PropertyIterator; import javax.servlet.Servlet; import javax.servlet.ServletException; import java.io.IOException; import java.io.PrintWriter; @Component( service = Servlet.class ) @SlingServletResourceTypes( resourceTypes = "/apps/local-project/components/servletresource", methods = HttpConstants.METHOD_GET ) public class AssetResourceServlet extends SlingSafeMethodsServlet { @Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println("Get Invoked"); try(ResourceResolver resolver = request.getResourceResolver()){ Resource resource = resolver.getResource("/content/dam/Sample/sun.jpg"); Node asset = resource.adaptTo(Node.class); Node metadata = asset.getNode("jcr:content").getNode("metadata"); out.println(metadata.getName()); PropertyIterator allProperties = metadata.getProperties(); if(allProperties.hasNext()){ while(allProperties.hasNext()){ Property property = allProperties.nextProperty(); out.println(property.getName()); } } }catch (Exception e){ e.printStackTrace(); } } }
Conclusion
Here we have learnt what are servlets, how they are registered and when to use which way to register it. Also we have tested both the servlets as registered by resource as well as by path.
I hope you enjoyed the learing and have found the blog informative.