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” }.
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.