AEM Developer Series
- Day 00: AEM Developer Series
- Day 01: Introduction to AEM
- Day 02: AEM Architecture
- Day 03: Setting up AEM Development Environment
- Day 04: Developing First OSGi Bundle
- Day 05: Working with Sling Servlets in AEM
- Day 06: Playing with Sling Post Servlet
- Day 07: Creating your first component in AEM
- Day 09: Dueling with Java User API
- Day 10: Getting to know Sling Models
- Day 11: Client Libraries in Action
- Day 12: Creating your custom OSGi Configuration
- Day 13: Schedulers in AEM
- Day 14: Eventing in AEM
- Day 15: Custom Workflows in AEM
- Day 16: Creating JMX Beans in AEM
- Day 17: Working with QueryBuilder API
- Day 18: Working with Granite Datasources in AEM
- Day 19: Replication API in Action
- Day 20: Working with Users and Groups in AEM
In this post, we are going to create a Sling Post servlet which is invoked by an HTTP POST call. We will make an AJAX call to achieve this.
Since this a POST request, we will be using SlingAllMethodsServlet as a parent to our custom servlet.
Sling Post Servlet Example
in this example, we will make an HTTP post request via AJAX to add a node at a path in the JCR. After adding the node, we will also modify the node by adding a name property.
- Create an AEM Multimodule project in eclipse (how? see here)
- Create a class SampleSlingPostServlet and paste the following code in it.
- Here we are registering the servlet via path /bin/submitdata. Property sling.servlet.methods define the HTTP method to be used i.e. POST in this case. Since we are writing the data, we have extended the class from SlingAllMethodsServlet.
- The logic in the doPost() creates a node under a given path and added a name property in it.
- Now to call this servlet via AJAX, create a new cq:component (how? see here) and in the HTML file of the component, add below code
- Note that the url property has the same path by which the servlet is registered.
- When we drag and drop the component on an AEM page, the post servlet will invoke and a node with name property will be created. You can check the same in CRXDE.
Congratulations!! 🙋 we have created a sling post servlet and invoked it via an AJAX call. I hope you enjoyed this post.
You can find the complete code of this project on my GitHub. Feel free to fork or open issues, if any.
I would love to hear your thoughts on this and would like to have suggestions from you to make it better.
Happy Coding 😊