What is Sling Servlet?
- Heena
- Jun 5, 2022
- 1 min read
Updated: May 2, 2024
Sling Servlet enables us to expose OSGI Service based on request - response model.
Every Sling Servlet must implement the Servlet interface which defines its lifecycle methods.
It must either extend SlingSafeMethodsServlet or SlingAllMethodsServlet
Servlet can either be path based(tagged to a specific paths) or resource based(tagged to specific resource types).
Lets create our first servlet:
Register Servlet as an OSGI Service.
@Component(
service={Servlet.class},
property={"sling.servlet.methods=post", "sling.servlet.paths=/bin/sampleservlet"})Available Properties:
2. Extend the SlingSafeMethodsServlet(if the servlet supports only GET) or SlingAllMethodsServlet
public class TestServlet extends SlingSafeMethodsServlet3. Override required methods. For GET we will override doGet()
@Override
protected void doGet(final SlingHttpServletRequest req, final SlingHttpServletResponse resp) throws IOException {
resp.setContentType("text/plain");
resp.getWriter().write("Test Successful");
}
Your servlet will look like:
package com.aemblog.core.servlets;
import java.io.IOException;
import javax.servlet.Servlet;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.osgi.service.component.annotations.Component;
@Component(service = Servlet.class, property = { "sling.servlet.paths=" + "/bin/testservlet",
"sling.servlet.methods=" + "GET" })
public class TestServlet extends SlingSafeMethodsServlet {
@Override
protected void doGet(final SlingHttpServletRequest req, final SlingHttpServletResponse resp) throws IOException {
resp.setContentType("text/plain");
resp.getWriter().write("Test Successful");
}
}4. Build and deploy the bundle. Following is the desired output:

That's all for today! If you've found this blog post informative or helpful, I’d greatly appreciate it if you could give it a like. It keeps me motivated 💛
Enjoying my ad-free blog? Support by buying me a coffee! I've kept this space ad-free, sponsoring it myself to maintain its purity. Your contribution would help keep the site afloat and ensure quality content. Thanks for being part of this ad-free community.


























