Expand my Community achievements bar.

Don’t miss the AEM Skill Exchange in SF on Nov 14—hear from industry leaders, learn best practices, and enhance your AEM strategy with practical tips.
SOLVED

posting data to Custom servlet in AEM6 to get the response from servlet.

Avatar

Level 2

http://stackoverflow.com/questions/32278952/posting-data-to-custom-servlet-in-aem6-

I'm trying to create a servlet in CQ. Then from my page will make an AJAX call posting data to Custom servlet in AEM6 to get the response from servlet.
My servlet class is below

package com.kicker.disolutions; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.URL; import java.rmi.ServerException; import java.util.Dictionary; import java.util.Enumeration; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.apache.sling.api.adapter.Adaptable; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceResolver; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Properties; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.Service; import org.apache.felix.scr.annotations.sling.SlingServlet; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.servlets.SlingSafeMethodsServlet; import org.apache.sling.commons.osgi.OsgiUtil; import org.apache.sling.jcr.api.SlingRepository; import org.apache.felix.scr.annotations.Reference; import org.osgi.service.component.ComponentContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.jcr.Session; import javax.jcr.Node; import org.json.simple.JSONObject; import java.util.UUID; @Component(immediate = true, metatype = false, label = "HelloFormServlet") @Service(PollController.class) @Properties(value = { @org.apache.felix.scr.annotations.Property(name = "sling.servlet.methods", value = "POST"), @org.apache.felix.scr.annotations.Property(name = "sling.servlet.paths", value ="/bin/HelloFormServlet") }) /*@SlingServlet(paths="/bin/HelloForm", methods = "POST", metatype=true)*/ public class PollController extends org.apache.sling.api.servlets.SlingAllMethodsServlet { private static final long serialVersionUID = 2598426539166789515L; Logger log=LoggerFactory.getLogger(PollController.class); /*  @Reference private SlingRepository repository; public void bindRepository(SlingRepository repository) { this.repository = repository; }*/ @Override protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServerException, IOException { try { log.info("getting values from jsp");
String feed = "This is some text from an external ASP file"; response.getWriter().write(feed); log.info("passing off jsp");
/*//Get the submitted form data that is sent from the //CQ web page String id = UUID.randomUUID().toString(); String firstName = request.getParameter("firstName"); String lastName = request.getParameter("lastName"); String address = request.getParameter("address"); String cat = request.getParameter("cat"); String state = request.getParameter("state"); String details = request.getParameter("details"); String date = request.getParameter("date"); String city = request.getParameter("city"); //Encode the submitted form data to JSON JSONObject obj=new JSONObject(); obj.put("id",id); obj.put("firstname",firstName); obj.put("lastname",lastName); obj.put("address",address); obj.put("cat",cat); obj.put("state",state); obj.put("details",details); obj.put("date",date); obj.put("city",city); //Get the JSON formatted data String jsonData = obj.toJSONString(); //Return the JSON formatted data response.getWriter().write(jsonData); */} catch(Exception e) { e.printStackTrace(); } } }

My JSP

<%@include file="/libs/foundation/global.jsp"%> <% %><%@page session="false" %><% %><% // TODO add you code here %> <%@page import="com.kicker.disolutions.*"%> <%@ page import="java.util.*"%> <%@ page import="java.io.*;"%> <%@page session="false"%> <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <cq:includeClientLib categories="jquerysamples" /> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script> $(document).ready(function() { alert("READY"); $('#submit').click(function() { var failure = function(err) { alert("Unable to retrive data "+err); }; alert("in submit"); var claimId = 2; //Use JQuery AJAX request to post data to a Sling Servlet $.ajax({ type: 'POST', url:'/bin/HelloFormServlet', data:'id='+ claimId, error:failure, success: function(msg){ alert(msg); $("#piechart").html(msg); } }); }); }); </script> </head> <body> <div>r u satisfied?</div><br> <input type="radio" name="ans" value="yes">Yes<br> <input type="radio" name="ans" value="no">NO<br> <div>r u satisfied?</div><br> <input type="radio" name="ans1" value="yes">Yes<br> <input type="radio" name="ans1" value="no">NO<br> <input id= "submit" type="submit" value="Submit" /><br> <div id="piechart" style="width: 900px; height: 500px;"></div> </body> </html>

After execution my error is below

29.08.2015 00:53:18.386 *ERROR* [0:0:0:0:0:0:0:1 [1440789798381] POST /bin/HelloFormServlet HTTP/1.1] org.apache.sling.servlets.post.impl.operations.ModifyOperation Unable to create resource named HelloFormServlet in /bin 29.08.2015 00:53:18.387 *ERROR* [0:0:0:0:0:0:0:1 [1440789798381] POST /bin/HelloFormServlet HTTP/1.1] org.apache.sling.servlets.post.impl.operations.ModifyOperation Exception during response processing. javax.jcr.nodetype.ConstraintViolationException: No default node type available for /bin/HelloFormServlet at org.apache.jackrabbit.oak.util.TreeUtil.addChild(TreeUtil.java:185) at org.apache.jackrabbit.oak.jcr.delegate.NodeDelegate.addChild(NodeDelegate.java:692) at org.apache.jackrabbit.oak.jcr.session.NodeImpl$5.perform(NodeImpl.java:286) at org.apache.jackrabbit.oak.jcr.session.NodeImpl$5.perform(NodeImpl.java:253) at org.apache.jackrabbit.oak.jcr.delegate.SessionDelegate.perform(SessionDelegate.java:308) at org.apache.jackrabbit.oak.jcr.session.ItemImpl.perform(ItemImpl.java:113) at org.apache.jackrabbit.oak.jcr.session.NodeImpl.addNode(NodeImpl.java:253) at org.apache.jackrabbit.oak.jcr.session.NodeImpl.addNode(NodeImpl.java:238) at org.apache.sling.jcr.resource.internal.helper.jcr.JcrResourceProvider.create(JcrResourceProvider.java:437) at org.apache.sling.resourceresolver.impl.tree.ResourceProviderEntry.create(ResourceProviderEntry.java:479) at org.apache.sling.resourceresolver.impl.ResourceResolverImpl.create(ResourceResolverImpl.java:1053) at org.apache.sling.servlets.post.impl.operations.AbstractCreateOperation.deepGetOrCreateNode(AbstractCreateOperation.java:578) at org.apache.sling.servlets.post.impl.operations.AbstractCreateOperation.processCreate(AbstractCreateOperation.java:105) at org.apache.sling.servlets.post.impl.operations.ModifyOperation.doRun(ModifyOperation.java:91)

Please help.. tried link but didn't help

1 Accepted Solution

Avatar

Correct answer by
Level 9

Hello,

Couple of things.

1. change @Service(PollController.class) to @Service(Servlet.class) because this the service it should be registering in

2. i think you should use a selector .html in your servlet paths because by default the /bin will be accessible with .html based on default configuration. check "Apache Sling Servlet/Script Resolver and Error Handler" in osgi console under configuration tab. /system/console/configMgr 

and if you want to use your own selector then you have to provide information there else default configuration will be not used or will be not allowed.

3. also check post servlet configuration under same tab

 

Let me know if it doesn't work.

 

Thanks,

Pawan

View solution in original post

4 Replies

Avatar

Correct answer by
Level 9

Hello,

Couple of things.

1. change @Service(PollController.class) to @Service(Servlet.class) because this the service it should be registering in

2. i think you should use a selector .html in your servlet paths because by default the /bin will be accessible with .html based on default configuration. check "Apache Sling Servlet/Script Resolver and Error Handler" in osgi console under configuration tab. /system/console/configMgr 

and if you want to use your own selector then you have to provide information there else default configuration will be not used or will be not allowed.

3. also check post servlet configuration under same tab

 

Let me know if it doesn't work.

 

Thanks,

Pawan

Avatar

Level 10

See this community article - it has an example package to so you can see it in action: 

https://helpx.adobe.com/experience-manager/using/custom-sling-servlets.html

Also - from the above exception - it looks like the bundle containing the servlet was not in an active state. Therefore AEM was not able to find it. 

Avatar

Level 2

smacdonald2008 wrote...

See this community article - it has an example package to so you can see it in action: 

https://helpx.adobe.com/experience-manager/using/custom-sling-servlets.html

Also - from the above exception - it looks like the bundle containing the servlet was not in an active state. Therefore AEM was not able to find it. 

 


i have installed the package in the url at home AEM6 which is having the same issue. but at the office the package is working.

Anyways ..the component for the servlet is in registered state at system/console/components. how to make this active?

Avatar

Level 2

Hi Pawan,

Thanks for the prompt response. I followed ur first point, this itself resolved my issue.

The posting data is happening and I also checked the Sling-> Sling Servlet Resolver at http://localhost:4502/system/console/configMgr , which is working fine. by giving "/bin/HelloFormServlet" at is picking the "PollController"

Again Thanks for correcting me yesyesyes