Sling servlets
Purpose: Build custom HTTP endpoints the Sling way — registered by resourceType, not by path.
Who this page is for
| Audience | Why it matters to you |
|---|
| Backend engineers | For 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?
| Registration | Problems |
|---|
| 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 resourceType | Inherits content permissions, context, caching semantics — use this unless truly content-independent |
Method classes
| Base class | For |
|---|
| SlingSafeMethodsServlet | GET/HEAD (read-only) |
| SlingAllMethodsServlet | +POST/PUT/DELETE — must handle CSRF (framework token for AJAX POSTs) |
Rules
- GET endpoints must be idempotent and cache-aware (they will be cached by the dispatcher if they match cache rules — decide deliberately).
- Validate selectors/suffix input; they are user input like any query param.
- Return proper status codes; HTML error bodies from servlets confuse JSON clients.
- For writes, prefer POST + CSRF token + service-user-mediated repository access.