Calling POST Servlet using resourceTypes,selectors and extensions in AEM

Saw some query on Adobe community forum on how to make a POST call to a servlet using sling.servlet.resourceTypes and using selectors. So here I am with my short article on how we can call a POST servlet using the same.

Creating a resource in crx:
Let’s say I have a node in AEM crx at /etc/mycompany/paths/states and add the resourceType on states node i.e mycompany/servlets/states


Once we are done creating the resource in CRX, we will create a corresponding JAVA class and define this resourceType along with selectors and extension to load the data.

@Component(service = Servlet.class, property = {
		Constants.SERVICE_DESCRIPTION + "=" + "Servlet to get the States details",
		ServletResolverConstants.SLING_SERVLET_METHODS + "=" + HttpConstants.METHOD_POST,
		ServletResolverConstants.SLING_SERVLET_RESOURCE_TYPES + "=" + "mycompany/servlets/states",
		ServletResolverConstants.SLING_SERVLET_SELECTORS + "=" + "api.getStates",
		ServletResolverConstants.SLING_SERVLET_EXTENSIONS + "=" + "json" })
public class GetStateDetailsServlet extends SlingAllMethodsServlet {

	private static final long serialVersionUID = 1L;

	private static final Logger LOG = LoggerFactory.getLogger(GetStateDetailsServlet.class);

	@Override
	protected void doPost(final SlingHttpServletRequest request, final SlingHttpServletResponse response) {
		
				response.getWriter().println("Hello World!!");
			
	}
}



Once we are done creating the corresponding servlet for using below property:

1. sling.servlet.resourceTypes : We provide the resourceType of the CRX node.
2. sling.servlet.selectors : We provide the selectors for our servlet URL.
3. sling.servlet.extensions : We provide the extension which we want to use along with the selectors to load the response.

So, the final end point that we will access to get the response will be something like this localhost:4502/etc/mycompany/paths/states.api.getStates.json




Thanks for reading. Let me know if I missed anything or we need any addition.
Happy Coding!!

Author:

I am Nikhil Kumar, AEM developer. Working on AEM since the start of my career. Created this blog to share my AEM knowledge and give back to the AEM Community. You can reach out to me on any query.

Leave a comment