Skip to main content

Sling Servlets in AEM - Complete Guide

Updated 6 min readMarkdown
Part of seriesApache Sling Series

In the previous post, we explored Sling Resource Resolution, which forms the foundation of how AEM maps HTTP requests to content. In this post, we’ll dive into Sling Servlets, the next key building block for handling requests, processing logic, and delivering responses in AEM.

Sling Servlets are central to AEM development, they allow developers to add custom logic for specific resources, paths, or selectors, enabling dynamic and content-driven responses.


What is a Sling Servlet?

A Sling Servlet is a Java class that implements the javax.servlet.Servlet interface and is registered with the Sling framework. Unlike traditional servlets that rely solely on URL mappings in web.xml, Sling Servlets are registered in OSGi and dynamically mapped to resources, paths, or selectors.

Sling Servlets can handle:

  • HTTP Methods: GET, POST, PUT, DELETE, etc.

  • Selectors and Extensions: e.g., /content/site/page.print.a4.html

  • Resource Types: Mapping logic to specific components or content nodes


Servlet Registration in Sling

Sling Servlets are registered via OSGi annotations, making them modular and dynamic:

1. By Resource Type

Handles requests for a specific component/resource.

@Component(service = Servlet.class,
           property = {
               "sling.servlet.resourceTypes=cq:Page",
               "sling.servlet.methods=GET",
               "sling.servlet.selectors=print",
               "sling.servlet.extensions=html"
           })
public class PrintPageServlet extends SlingSafeMethodsServlet {
    @Override
    protected void doGet(SlingHttpServletRequest request,
                         SlingHttpServletResponse response) throws ServletException, IOException {
        response.getWriter().write("Printing page content...");
    }
}

How it works:

  • sling.servlet.resourceTypes → The type of resource this servlet handles.

  • sling.servlet.methods → Allowed HTTP methods.

  • sling.servlet.selectors and sling.servlet.extensions → Request filtering.


2. By Path

Handles requests for a specific URL path.

@Component(service = Servlet.class,
           property = {
               "sling.servlet.paths=/bin/custom/hello",
               "sling.servlet.methods=GET"
           })
public class HelloServlet extends SlingSafeMethodsServlet {
    @Override
    protected void doGet(SlingHttpServletRequest request,
                         SlingHttpServletResponse response) throws ServletException, IOException {
        response.getWriter().write("Hello from /bin/custom/hello");
    }
}

How it works:

  • sling.servlet.paths → Directly maps a URL path to a servlet.

  • Useful for tooling endpoints like /bin scripts or JSON APIs.


Selectors, Extensions, and HTTP Methods

Sling supports Selectors and Extensions to refine request routing:

Example request:

/content/site/page.print.a4.html
  • Selectors: print.a4

  • Extension: html

  • The servlet will only execute if its selectors/extensions match.

HTTP methods are handled using:

  • SlingSafeMethodsServlet → For safe methods (GET, HEAD, OPTIONS)

  • SlingAllMethodsServlet → For all methods, including POST, PUT, DELETE


Integration with OSGi Services

Sling Servlets are themselves OSGi components. This means you can inject services directly:

@Component(service = Servlet.class,
           property = {
               "sling.servlet.resourceTypes=cq:Page",
               "sling.servlet.methods=GET"
           })
public class PageInfoServlet extends SlingSafeMethodsServlet {

    @Reference
    private ResourceResolverFactory resolverFactory;

    @Override
    protected void doGet(SlingHttpServletRequest request,
                         SlingHttpServletResponse response) throws ServletException, IOException {
        response.getWriter().write("ResourceResolverFactory injected successfully!");
    }
}

Key Points:

  • Only OSGi components can inject OSGi services.

  • You can combine Sling Servlets with OSGi services, Sling Models, and adaptables for clean and modular design.


Best Practices for Sling Servlets

  1. Use Resource Types over Paths whenever possible for content-driven logic.

  2. Keep servlets stateless; rely on injected services for shared operations.

  3. Use selectors for multiple representations (e.g., .print.html, .json).

  4. Avoid hardcoding /bin paths for content-related logic; /bin is usually reserved for tooling.

  5. Always handle HTTP method restrictions correctly for safety and security.


Example: GET/POST for a Contact Form

@Component(service = Servlet.class,
           property = {
               "sling.servlet.resourceTypes=components/contactform",
               "sling.servlet.methods=GET,POST",
               "sling.servlet.extensions=html"
           })
public class ContactFormServlet extends SlingAllMethodsServlet {

    @Override
    protected void doGet(SlingHttpServletRequest request,
                         SlingHttpServletResponse response) throws ServletException, IOException {
        response.getWriter().write("Render contact form...");
    }

    @Override
    protected void doPost(SlingHttpServletRequest request,
                          SlingHttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        String email = request.getParameter("email");
        response.getWriter().write("Received submission: " + name + ", " + email);
    }
}

GET Request Example

URL in browser:

http://localhost:4502/content/site/en/contact.html

Behavior:

  • GET request is routed to the ContactFormServlet because the resource type of /content/site/en/contact is components/contactform.

  • The servlet renders the contact form on the page.


POST Request Example

HTML form submission:

<form action="/content/site/en/contact.html" method="post">
  <input type="text" name="name" placeholder="Your Name" />
  <input type="email" name="email" placeholder="Your Email" />
  <button type="submit">Submit</button>
</form>

Behavior:

  • POST request is routed to the same servlet.

  • Servlet processes submitted data using request.getParameter("name") and request.getParameter("email").

  • Returns confirmation or further processing (e.g., store in JCR or send email).


SlingSafeMethodsServlet

Purpose:
Designed for handling “safe” HTTP methods – methods that do not modify server state. These are typically read-only operations.

Safe Methods:

  • GET

  • HEAD

  • OPTIONS

Characteristics:

  • Only implements doGet, doHead, doOptions, etc.

  • Any attempt to handle a modifying method (POST, PUT, DELETE) will result in 405 Method Not Allowed by default.

  • Ideal for rendering content, such as page rendering or returning data without changing the repository.

Example:

@Component(service = Servlet.class,
           property = {
               "sling.servlet.resourceTypes=components/page",
               "sling.servlet.methods=GET"
           })
public class PageRenderServlet extends SlingSafeMethodsServlet {
    @Override
    protected void doGet(SlingHttpServletRequest request,
                         SlingHttpServletResponse response) throws ServletException, IOException {
        response.getWriter().write("Rendering page content...");
    }
}

✅ Use Case: Fetching content, displaying pages, REST GET APIs that do not change state.


SlingAllMethodsServlet

Purpose:
Handles all HTTP methods, including safe and unsafe methods. Unsafe methods can modify server state.

Supported Methods:

  • GET, HEAD, OPTIONS (safe)

  • POST, PUT, DELETE, PATCH (unsafe)

Characteristics:

  • Implements doGet(), doPost(), doPut(), doDelete(), etc.

  • Allows both read and write operations.

  • Useful for forms, content updates, and APIs that change data in the repository.

Example:

@Component(service = Servlet.class,
           property = {
               "sling.servlet.resourceTypes=components/contactform",
               "sling.servlet.methods=GET,POST"
           })
public class ContactFormServlet extends SlingAllMethodsServlet {
    @Override
    protected void doGet(SlingHttpServletRequest request,
                         SlingHttpServletResponse response) throws ServletException, IOException {
        response.getWriter().write("Render contact form...");
    }

    @Override
    protected void doPost(SlingHttpServletRequest request,
                          SlingHttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        response.getWriter().write("Received: " + name);
    }
}

✅ Use Case: Forms, APIs, POST/PUT actions that modify content in JCR.


Key Differences Table

Feature SlingSafeMethodsServlet SlingAllMethodsServlet
HTTP Methods Only safe (GET, HEAD, OPTIONS) Safe + unsafe (GET, POST, PUT, DELETE, etc.)
Default Handling of Unsafe Methods 405 Method Not Allowed Can implement unsafe methods
Typical Use Reading content, rendering pages Reading + writing content, forms, API endpoints
Example Page rendering servlet Contact form servlet, CRUD APIs

💡 Rule of Thumb:

  • Use SlingSafeMethodsServlet for read-only endpoints.

  • Use SlingAllMethodsServlet for endpoints that handle user input or modify repository content.


What’s Next?

In the next post, we’ll explore Sling Models:

  • How to map JCR nodes/resources to POJOs.

  • How dependency injection works in Sling Models.

  • Using @Inject, @ValueMapValue, and @OSGiService for clean templates.

This will build on servlets and resource resolution to create modular, maintainable code in AEM.

No comments yet. Be the first to comment.