Expand my Community achievements bar.

Dive into Adobe Summit 2024! Explore curated list of AEM sessions & labs, register, connect with experts, ask questions, engage, and share insights. Don't miss the excitement.
SOLVED

AEM 6.1 form submit, redirect to same page and display result using Sightly

Avatar

Former Community Member

I am trying to do the following on AEM 6.1:

  1. Develop a simple form (3 input fields)
  2. Process the submitted values,
  3. And redirect to the same page with processed values/result

I am able to submit the values to a servlet, and process them (business logic), ad the result to a requestparamter so i an retrieve them on the UI. But i am stuck at these:

  1. Redirecting to the same page
  2. And retrieving the request parameters and display them using Sightly

In my SlingServlet.. i have the result as a string. I wanted to redirect to the same page and display the value in result using Sightly.

1 Accepted Solution

Avatar

Correct answer by
Former Community Member

After a lot of research and trials i found the solution. Posted my notes here:

http://stackoverflow.com/questions/31454357/aem-6-1-sightly-basic-form-submit-and-redirect-to-same-p...

Here's the solution:

Result Form with response from webservice:

[img]PostForm-Step2-condensed.JPG[/img]

Process flow

 1. Submit form data to Servlet's POST method
 2. In Servlet, get the values entered by the user from the request
 3. Make the necessary webservice calls. Get the response(json)
 4. I added the response-json as a parameter to the request
 5. Using Wrapper, forward to the necessary page
 6. Define a WCMUse class for use with Sightly.
 7. Assign the 'request' to the Use-class and process it there
 8. Use the assigned values from the Use-class to the UI using sightly 

Code snippets - HTML

<form name="userRegistrationForm" method="post" action="/services/processFormData"> <input type="hidden" name=":redirect" value="posttest.html" /> <input type="submit" title="Submit" class="btn submit btn-success" value="Submit" tabindex="25" name="bttnAction"> <div data-sly-use.model="${'com.tti.tticommons.service.helpers.PostServiceHelper' @ slingreq=request }"> **${model.getRawJson}** </div>

   

Code snippets - Servlet

@SlingServlet( label = "TTI - TTICommon Servlet", metatype = true, methods = { "POST" }, name="com.tti.tticommons.service.servlets.TTIPostServlet", paths = { "/services/processFormData" } ) public class TTIPostServlet extends SlingAllMethodsServlet{ @Override protected void doPost(SlingHttpServletRequest request,SlingHttpServletResponse response) throws ServletException,IOException { log.info("\n\n----- TTIPostServlet POST: "); String paramName; String paramValue; String osgiService=""; try { Enumeration<String> parameterNames = request.getParameterNames(); Map<String, String> formParametersMap = new HashMap<String, String>(); while (parameterNames.hasMoreElements()) { paramName = parameterNames.nextElement(); paramValue = request.getParameter(paramName); if (paramName.equals("osgiService")) { osgiService = paramValue; } else if (paramName.equals(":cq_csrf_token")) { //TODO: don't add to the map } else if (paramName.equals("bttnAction")) { //TODO: dont' add to the map } else { //log.info("\n---ParamName="+paramName+", value="+paramValue); formParametersMap.put(paramName, paramValue); } } String parametersInJSON = JSONHelper.toJson(formParametersMap); log.info("\n\n----------- POST paramters in json="+parametersInJSON); String json = webServiceHelper.getJSON(osgiService, parametersInJSON, request, response); log.info("\n\n----------- POST json from web service="+json); request.setAttribute("jsonResponse",json); //String redirectPage =  request.getParameter(":redirect"); //RequestDispatcher dispatcher = request.getRequestDispatcher("/content/ttii/en/"+redirectPage); RequestDispatcher dispatcher = request.getRequestDispatcher("/content/ttii/en/postformtest.html"); GetRequest getRequest = new GetRequest(request); dispatcher.forward(getRequest, response); } catch (Exception e) { log.error("SlingServlet Failed while retrieving resources"); } finally { //TODO } } /** Wrapper class to always return GET for AEM to process the request/response as GET. */ private static class GetRequest extends SlingHttpServletRequestWrapper { public GetRequest(SlingHttpServletRequest wrappedRequest) { super(wrappedRequest); } @Override public String getMethod() { return "GET"; } }    


Code snippets - PostServiceHelper - WCMUSe class

public class PostServiceHelper extends WCMUse { protected final Logger log = LoggerFactory.getLogger(PostServiceHelper.class); private SlingHttpServletRequest httpRequest; private String rawJson; @Override public void activate() throws Exception { log.info("\n\n========= PostServiceHelper.activate():"+get("slingreq", SlingHttpServletRequest.class)); this.httpRequest = get("slingreq", SlingHttpServletRequest.class); //this.resourceResolver = getResourceResolver(); //log.info("\n\n========= getRequest()="+getRequest()); SlingHttpServletRequest tRequest; Set<String> keys = new HashSet<String>(); Enumeration<?> attrNames = this.httpRequest.getAttributeNames(); while (attrNames.hasMoreElements()) { String attr = (String) attrNames.nextElement(); //log.info("\n--- Key="+attr); if (attr.equals("jsonResponse")) { this.setRawJson((String)this.httpRequest.getAttribute(attr)); //log.info("\n---rawJson is SET with : "+this.rawJson); } } } public void setRawJson(String json) { this.rawJson = json; } public String getRawJson() { return this.rawJson; } }

View solution in original post

4 Replies

Avatar

Correct answer by
Former Community Member

After a lot of research and trials i found the solution. Posted my notes here:

http://stackoverflow.com/questions/31454357/aem-6-1-sightly-basic-form-submit-and-redirect-to-same-p...

Here's the solution:

Result Form with response from webservice:

[img]PostForm-Step2-condensed.JPG[/img]

Process flow

 1. Submit form data to Servlet's POST method
 2. In Servlet, get the values entered by the user from the request
 3. Make the necessary webservice calls. Get the response(json)
 4. I added the response-json as a parameter to the request
 5. Using Wrapper, forward to the necessary page
 6. Define a WCMUse class for use with Sightly.
 7. Assign the 'request' to the Use-class and process it there
 8. Use the assigned values from the Use-class to the UI using sightly 

Code snippets - HTML

<form name="userRegistrationForm" method="post" action="/services/processFormData"> <input type="hidden" name=":redirect" value="posttest.html" /> <input type="submit" title="Submit" class="btn submit btn-success" value="Submit" tabindex="25" name="bttnAction"> <div data-sly-use.model="${'com.tti.tticommons.service.helpers.PostServiceHelper' @ slingreq=request }"> **${model.getRawJson}** </div>

   

Code snippets - Servlet

@SlingServlet( label = "TTI - TTICommon Servlet", metatype = true, methods = { "POST" }, name="com.tti.tticommons.service.servlets.TTIPostServlet", paths = { "/services/processFormData" } ) public class TTIPostServlet extends SlingAllMethodsServlet{ @Override protected void doPost(SlingHttpServletRequest request,SlingHttpServletResponse response) throws ServletException,IOException { log.info("\n\n----- TTIPostServlet POST: "); String paramName; String paramValue; String osgiService=""; try { Enumeration<String> parameterNames = request.getParameterNames(); Map<String, String> formParametersMap = new HashMap<String, String>(); while (parameterNames.hasMoreElements()) { paramName = parameterNames.nextElement(); paramValue = request.getParameter(paramName); if (paramName.equals("osgiService")) { osgiService = paramValue; } else if (paramName.equals(":cq_csrf_token")) { //TODO: don't add to the map } else if (paramName.equals("bttnAction")) { //TODO: dont' add to the map } else { //log.info("\n---ParamName="+paramName+", value="+paramValue); formParametersMap.put(paramName, paramValue); } } String parametersInJSON = JSONHelper.toJson(formParametersMap); log.info("\n\n----------- POST paramters in json="+parametersInJSON); String json = webServiceHelper.getJSON(osgiService, parametersInJSON, request, response); log.info("\n\n----------- POST json from web service="+json); request.setAttribute("jsonResponse",json); //String redirectPage =  request.getParameter(":redirect"); //RequestDispatcher dispatcher = request.getRequestDispatcher("/content/ttii/en/"+redirectPage); RequestDispatcher dispatcher = request.getRequestDispatcher("/content/ttii/en/postformtest.html"); GetRequest getRequest = new GetRequest(request); dispatcher.forward(getRequest, response); } catch (Exception e) { log.error("SlingServlet Failed while retrieving resources"); } finally { //TODO } } /** Wrapper class to always return GET for AEM to process the request/response as GET. */ private static class GetRequest extends SlingHttpServletRequestWrapper { public GetRequest(SlingHttpServletRequest wrappedRequest) { super(wrappedRequest); } @Override public String getMethod() { return "GET"; } }    


Code snippets - PostServiceHelper - WCMUSe class

public class PostServiceHelper extends WCMUse { protected final Logger log = LoggerFactory.getLogger(PostServiceHelper.class); private SlingHttpServletRequest httpRequest; private String rawJson; @Override public void activate() throws Exception { log.info("\n\n========= PostServiceHelper.activate():"+get("slingreq", SlingHttpServletRequest.class)); this.httpRequest = get("slingreq", SlingHttpServletRequest.class); //this.resourceResolver = getResourceResolver(); //log.info("\n\n========= getRequest()="+getRequest()); SlingHttpServletRequest tRequest; Set<String> keys = new HashSet<String>(); Enumeration<?> attrNames = this.httpRequest.getAttributeNames(); while (attrNames.hasMoreElements()) { String attr = (String) attrNames.nextElement(); //log.info("\n--- Key="+attr); if (attr.equals("jsonResponse")) { this.setRawJson((String)this.httpRequest.getAttribute(attr)); //log.info("\n---rawJson is SET with : "+this.rawJson); } } } public void setRawJson(String json) { this.rawJson = json; } public String getRawJson() { return this.rawJson; } }

Avatar

Level 10

WHy not use AJAX and JS - process the return value and set the fields on the page using JQUery selectors.

//Use JQuery AJAX request to post data to a Sling Servlet
    $.ajax({
         type: 'POST',    
         url:'/bin/mySearchServlet',
         data:'id='+ claimId+'&firstName='+ myFirst+'&lastName='+ myLast+'&address='+ address+'&cat='+ cat+'&state='+ state+'&details='+ details+'&date='+ date+'&city='+ city,
         success: function(msg){
 
           var json = jQuery.parseJSON(msg); 
            var msgId=   json.id;
            var lastName = json.lastname;
            var firstName = json.firstname;
              
            $('#ClaimNum').val(msgId); 
            $('#json').val("Filed by " + firstName + " " + lastName);   
         }
     });
  });

 

 

 

 See this article and how we process the returned JSON and set fields:

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

Avatar

Level 10
Great solution. I am going to reproduce.       

Avatar

Former Community Member

smacdonald2008 wrote...

WHy not use AJAX and JS - process the return value and set the fields on the page using JQUery selectors.

//Use JQuery AJAX request to post data to a Sling Servlet
    $.ajax({
         type: 'POST',    
         url:'/bin/mySearchServlet',
         data:'id='+ claimId+'&firstName='+ myFirst+'&lastName='+ myLast+'&address='+ address+'&cat='+ cat+'&state='+ state+'&details='+ details+'&date='+ date+'&city='+ city,
         success: function(msg){
 
           var json = jQuery.parseJSON(msg); 
            var msgId=   json.id;
            var lastName = json.lastname;
            var firstName = json.firstname;
              
            $('#ClaimNum').val(msgId); 
            $('#json').val("Filed by " + firstName + " " + lastName);   
         }
     });
  });

 

 

 

 See this article and how we process the returned JSON and set fields:

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

 

Thanks, that maybe an option but we did not want to use JQuery. 

The following has evaluated to null or missing: ==> liqladmin("SELECT id, value FROM metrics WHERE id = 'net_accepted_solutions' and user.id = '${acceptedAnswer.author.id}'").data.items [in template "analytics-container" at line 83, column 41] ---- Tip: It's the step after the last dot that caused this error, not those before it. ---- Tip: If the failing expression is known to be legally refer to something that's sometimes null or missing, either specify a default value like myOptionalVar!myDefault, or use <#if myOptionalVar??>when-present<#else>when-missing. (These only cover the last step of the expression; to cover the whole expression, use parenthesis: (myOptionalVar.foo)!myDefault, (myOptionalVar.foo)?? ---- ---- FTL stack trace ("~" means nesting-related): - Failed at: #assign answerAuthorNetSolutions = li... [in template "analytics-container" at line 83, column 5] ----