In this session, we will see how to manage Sling requests using Java Servlets. Servlets are programs that run on a Web server and act as a middle layer between a request and a response. You can deploy Servlets in the Felix console and use them for managing the request from clients. An example: you need to print a message for the request coming from a certain path. Something like, “Thanks for the patience – Coming soon,” because the page is not yet ready.
- Import the following classes:
import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.servlets.SlingSafeMethodsServlet; import org.apache.felix.scr.annotations.sling.SlingServlet;
- Add the following Sling Servlet annotation:
@SlingServlet(paths="/customer/casestudy", methods="GET")
You can also use more generic scr plugin annotation as follows:
@Properties({ @Property(name = "sling.servlet.resourceTypes", value = "sling/servlet/default"), @Property(name = "sling.servlet.methods", value = "GET") }) - Ensure that the class extends SlingSafeMethodsServlet.This class is used to read data in Sling. Since we extended a serializable class, add the version number associated with a serializable class. It’s not Sling-specific; it is specific to serializable classes in Java.
- Create a doGet() method as follows:
If you don’t have a doGet() method, the response throws an error.public void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException { response.setHeader("Content-Type", "application/json"); response.getWriter().print("Thanks for the patience. Coming soon!!"); } - Build the project after deleting the existing bundle.
- Check if you can resolve the path to the correct servlet.
- Log into the system/console.
- Go to Sling > Sling Servlet Resolver.
- Enter bin/casestudy.
- Now access the node http://localhost:4502/customer/casestudy.
- Note that it displays the response.
That’s about the session. See you soon.
Here is the complete class:
package com.aemcompany.myproject.impl;
import java.io.IOException;
import org.apache.felix.scr.annotations.sling.SlingServlet;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
@SlingServlet(paths="/bin/casestudy", methods="GET")
public class ServletResponse extends SlingSafeMethodsServlet{
private static final long serialVersionUID = 1L;
public void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException
{
response.setHeader("Content-Type", "application/json");
response.getWriter().print("Thanks for the patience. Coming soon!!");
}
}
Leave a comment