@SlingServletPaths Example Code in AEM

This is a quick reference to example code, which will show you how to use the most base instantiation of @SlingServletPaths. The output is a simple JSON response with application/JSON, 200 OK, and response body = { “property1”: “value1” }.

Quick note:
it’s not recommended to use @SlingServletPaths. Check out the caveats when implementing servlets with path, @SlingServletPaths, https://sourcedcode.com/blog/aem/registering-slingservletpaths-component-property-type
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.sourcedcode.core.servlets;

import com.google.gson.JsonObject;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.apache.sling.servlets.annotations.SlingServletPaths;
import org.osgi.service.component.annotations.Component;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import java.io.IOException;

@Component(service = Servlet.class)
@SlingServletPaths("/bin/example")
public class FindContentFragmentServlet extends SlingSafeMethodsServlet {

    @Override
    protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json");
        JsonObject jo = new JsonObject();
        jo.addProperty("property1", "value1");
        response.getWriter().write(jo.toString());
        response.setStatus(SlingHttpServletResponse.SC_OK);
    }
}

Example of Servlet Being Called

Test: When I call http://localhost:4502/bin/example, I expect to see a JSON response with application/JSON, 200 OK, and response body = { “property1”: “value1” }. The example shows that the tests are passing.


Hello, I am an enthusiastic Adobe Community Advisor and a seasoned Lead AEM Developer. I am currently serving as an AEM Technical Lead at MNPDigital.ca, bringing over a decade of extensive web engineering experience and more than eight years of practical AEM experience to the table. My goal is to give back to the AEM Full Stack Development community by sharing my wealth of knowledge with others. You can connect with me on LinkedIn.

Leave a Reply

Your email address will not be published. Required fields are marked *


Back To Top