April 10, 2020
Estimated Post Reading Time ~

Playing with Sling Post Servlet

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.
  • Create a class SampleSlingPostServlet and paste the following code in it.

package org.redquark.demo.core.servlets;

import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.servlet.Servlet;

import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.PersistenceException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.servlets.HttpConstants;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.osgi.framework.Constants;
import org.osgi.service.component.annotations.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Anirudh Sharma
 *
 * This class shows the usage of SlingPostServlet
 */
@Component(service = Servlet.class, property = {
 Constants.SERVICE_DESCRIPTION + "=Simple Demo Servlet",
 "sling.servlet.methods=" + HttpConstants.METHOD_POST,
 "sling.servlet.paths=" + "/bin/submitdata"
})
public class SampleSlingPostServlet extends SlingAllMethodsServlet {

 /**
  * Generated serialVersionUID
  */
 private static final long serialVersionUID = -159625176093879129 L;

 /**
  * Logger
  */
 private static final Logger log = LoggerFactory.getLogger(SampleSlingPostServlet.class);

 /**
  * Overridden doPost() method which is invoked when an HTTP post request is made
  */
 @Override
 protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) {

  try {

   /**
    * Getting the instance of resource resolver from the request
    */
   ResourceResolver resourceResolver = request.getResourceResolver();

   /**
    * Getting the resource object via path
    */
   Resource resource = resourceResolver.getResource("/content/demoproject/en");

   log.info("Resource is at path {}", resource.getPath());

   /**
    * Adapt the resource to javax.jcr.Node type
    */
   Node node = resource.adaptTo(Node.class);

   /**
    * Create a new node with name and primary type and add it below the path specified by the resource
    */
   Node newNode = node.addNode("demoNode", "nt:unstructured");

   /**
    * Setting a name property for this node
    */
   newNode.setProperty("name", "Demo Node");

   /**
    * Commit the changes to JCR
    */
   resourceResolver.commit();

  } catch (RepositoryException e) {

   log.error(e.getMessage(), e);

   e.printStackTrace();

  } catch (PersistenceException e) {

   log.error(e.getMessage(), e);

   e.printStackTrace();
  }
 }
}
  • 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 and in the HTML file of the component, add below code

AJAX call
for SampleSlingPostServlet

 <
 script >
 $.ajax({
  type: "POST",
  url: '/bin/submitdata',
  /*data : {         
  pass your request parameter here, currently we are not passing any data     
  },*/
  success: function(data, textStatus, jqXHR) {
   //write your logic that you need to perform on sucess                           
  },
  error: function(XMLHttpRequest, textStatus, errorThrown) {
   //write your logic that you need to perform on error     
  }
 }); <
/script>
  • 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.
CRXDE

Conclusion

Congratulations!! 🙋 we have created a sling post servlet and invoked it via an AJAX call. I hope you enjoyed this post. 


By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.