HomeBackend Development › Sling servlets

Sling servlets

Purpose: Build custom HTTP endpoints the Sling way — registered by resourceType, not by path.

Who this page is for

AudienceWhy it matters to you
Backend engineersFor AJAX endpoints, form handlers, integrations

ResourceType registration (the right default)

@Component(service = Servlet.class)
@SlingServletResourceTypes(
    resourceTypes = "phi-academy/components/planpage",
    selectors = "premium",
    extensions = "json",
    methods = HttpConstants.METHOD_GET)
public class PremiumServlet extends SlingSafeMethodsServlet {
    @Override
    protected void doGet(SlingHttpServletRequest req, SlingHttpServletResponse resp) throws IOException {
        Resource page = req.getResource();          // ← content context for free
        // …write JSON
    }
}

Now /content/phi/plans/gold-hospital.premium.json serves your endpoint with the page as context, ACL-checked against the requesting user, cacheable and dispatcher-filterable like any URL.

Why not path registration?

RegistrationProblems
By path (/bin/…)No resource context, bypasses content ACLs (runs even for paths that don't exist), needs its own dispatcher allow-rule, path collisions
By resourceTypeInherits content permissions, context, caching semantics — use this unless truly content-independent

Method classes

Base classFor
SlingSafeMethodsServletGET/HEAD (read-only)
SlingAllMethodsServlet+POST/PUT/DELETE — must handle CSRF (framework token for AJAX POSTs)

Rules

Quick navigation