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.2 invoke JSP code after HTTP POST request

Avatar

Level 4

Hi All,

Is it possible to invoke JSP code in AEM 6.2 following an HTTP POST request?

I have managed to get it working for HTTP GET but I can’t get it working for HTTP POST.

I have listed below the steps I have gone through so far to get JSP code running with HTTP GET and to try to get it working with HTTP POST.

Thank you for you help,
Best regards,
Robert

————

Here are the steps I have gone through so far :-

1. In browser, navigate to http://localhost:4502/crx/de/index.jsp#/apps
2. Create a Component called “simpleCounterIncrementer”
3. Paste the JSP code below into “simpleCounterIncrementer.jsp”

    <%@ page import = "javax.jcr.*,org.apache.sling.api.SlingHttpServletRequest,org.apache.sling.api.resource.ResourceResolver,org.apache.sling.api.resource.Resource" %>
    <%
    final String simpleCounterNode = "simpleCounterNode";

    final SlingHttpServletRequest slingRequest = (SlingHttpServletRequest) request;
    final ResourceResolver resourceResolver = slingRequest.getResourceResolver();
    final Resource resource = resourceResolver.getResource("/content");
    Node node = resource.adaptTo(Node.class);
    if (node.hasNode(simpleCounterNode))
    {
        node = node.getNode(simpleCounterNode);
    }
    else
    {
        node.addNode(simpleCounterNode);
        node.save();
        node = node.getNode(simpleCounterNode);
    }

    final String simpleCounterProperty = "simpleCounterProperty";

    if (!node.hasProperty(simpleCounterProperty))
    {
        node.setProperty(simpleCounterProperty, 0);
    }
    final Property counterProperty = node.getProperty(simpleCounterProperty);
    counterProperty.setValue(counterProperty.getLong() + 1);
    counterProperty.save();
    %>

4. In browser, navigate to http://localhost:4502/crx/de/index.jsp#/content
5. Create a Node called “simpleCounterIncrementer” and set “jcr:primaryType” = “cq:Page”
6. Create a sub-Node called “jcr:content” and set “jcr:primaryType” = “cq:PageContent” and set “sling:resourceType” = “simpleCounterIncrementer”

7. Open a terminal window and run the command below FIVE times

    curl --user admin:admin -X GET http://localhost:4502/content/simpleCounterIncrementer.html

8. In browser, navigate to http://localhost:4502/crx/de/index.jsp#/content/simpleCounterNode and observe "simpleCounterProperty" in 5 because HTTP GET has run five times

9. In browser, navigate to http://localhost:4502/crx/de/index.jsp#/apps/simpleCounterIncrementer

10. Copy “simpleCounterIncrementer.jsp”  and paste it as “simpleCounterIncrementer.POST.jsp”

11. Open a terminal window and run the command below

      curl --user admin:admin -X POST http://localhost:4502/content/simpleCounterIncrementer.html

12. In browser, navigate to http://localhost:4502/crx/de/index.jsp#/content/simpleCounterNode and observe "simpleCounterProperty" in still 5 even though HTTP POST has run


Please can you advise if it is possible to invoke JSP code in AEM 6.2 following an HTTP POST request?

Please can you advise what additional steps I need?

Thank you for your time,
Best regards,
Robert

1 Accepted Solution

Avatar

Correct answer by
Level 4

Thank you for your responses.  For the benefit of anyone else who wants a "simple" set of instructions how to create a POST request handler for AEM 6.2, here goes :-

1.  Install Maven and install Eclipse IDE for Java EE Developers

2.  Run the following Maven command to create the Java project in the current directory, and input properties when prompted :-

     mvn archetype:generate -DarchetypeGroupId=com.day.jcr.vault -DarchetypeArtifactId=multimodule-content-package-archetype -DarchetypeVersion=1.0.2 -DarchetypeRepository=adobe-public-releases

     groupId:  org.mytest
     artifactId:  mytest
     version:  1.0-SNAPSHOT
     package:  org.mytest
     appsFolderName:  myproject
     artifactName:  My Project
     cqVersion:  6.2
     packageGroup:  My Company

3.  From inside the mytest directory, run the following Maven command :-

     mvn eclipse:eclipse

4.  From Eclipse, goto File menu —-> Import —-> Existing Maven projects —-> mytest directory  ,  and ignore error during import

5.  Create a new Maven Build Run Configuration for the mytest-bundle directory (goals “clean install”) and test it builds JAR in bundle/target directory

6.  In Eclipse Package Explorer, in mytest-bundle, navigate to org.mytest package and add a new class SimplePostHandler  (JAVA CODE BELOW)

7.  Re-build mytest-bundle and check JAR in bundle/target directory has updated

8.  Navigate to http://localhost:4502/system/console/bundles

9.  Click Install/Update button , tick Start Bundle , and click Browse to select your JAR in bundle/target

10.  To test, run the following Curl command and check you get the expected response from your SimplePostHandler :-

      curl --user admin:admin -X POST --data "from=HELLO&to=WORLD" http://localhost:4502/bin/myPostHandler


Below is the Java code needed for step 6 :-


import org.apache.felix.scr.annotations.sling.SlingServlet;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;

@SlingServlet(paths="/bin/myPostHandler", methods="POST", metatype=true)
public class SimplePostHandler extends SlingAllMethodsServlet
{
    @Override
    protected void doPost(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
    {
        try
        {
            final String from = request.getParameter("from");
            final String to = request.getParameter("to");
            
            response.getWriter().write("Version 1.1 , from " + from + " to " + to + "\n");
        }
        catch (final Exception e)
        {
            e.printStackTrace();
        }
    }
}

View solution in original post

11 Replies

Avatar

Level 7
        Why you need to do this? Probably you can use a sling servlet in order to simplify/resolve it.

Avatar

Level 10

Correct - you are trying to do tasks that should be performed in a SLign Servlet - not JSP. 

Avatar

Level 7

Hi Robert,

As the above replies you could use a sling servlet to achieve this. Or is there any specific business requirement to use jsp, if not you could refer to the below url for reference.

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

Thanks

Tuhin

Avatar

Administrator

Hi

Please read Sling Request processing:

Link:- https://docs.adobe.com/docs/en/aem/6-2/develop/the-basics.html#Sling Request Processing

[img]https://docs.adobe.com/content/docs/en/aem/6-2/develop/the-basics/_jcr_content/contentbody/image_1.i...

Order of resolution is Exact match "selector.extention" >  "Selector" > "Extention" > worst case is Method type (that's why simpleCounterIncrementer.html is called rather than simpleCounterIncrementer.POST.html )

 

Secondly, the practice you are doing is not AEM Best practice. We should always create "Sling servlet to achieve this". 

As mentioned by Tuhin, please refer to :- https://helpx.adobe.com/experience-manager/using/custom-sling-servlets.html

 

Thanks and Regards

Kautuk Sahni



Kautuk Sahni

Avatar

Level 4

Thank you for responding.

In the tutorial https://helpx.adobe.com/experience-manager/using/custom-sling-servlets.html , in section "Add CSS and JQuery files to a cq:ClientLibraryFolder node." , it mentions :-

To add CSS files and the JQuery framework to your component, add a cq:ClientLibraryFolder node to your component.  After you create the node, set properties that allow the JSP script to find the CSS files and the JQuery library files.

Please can you advise me where I find the properties mentioned above or what the properties should be called?

I have created a cq:ClientLibraryFolder node to my component.   The only properties I see in my cq:ClientLibraryFolder node are jcr:created , jcr:CreatedBy and jcr:primaryType.

Thanks,

Robert

Avatar

Level 10

You use CRX DE lite to add these props to the client libs. 

Hope this helps... 

Avatar

Level 10

Also - the clientlibs have nothing to do with the functionality of the AEM Sling Servlet. In this example, the clientlibs drive the view of the JSP that invokes the Servlet. For example, it controls the font and the background color of the page. In your use case - you want to modify JCR nodes. It is much better to do so via the JCR API in a Sling Servlet. 

If you want, we can setup a connect session to discuss more. Let me know. 

Avatar

Employee Advisor

Hi,

Are you sure, that your JSP is actually called? You can check that with on /system/console/requests when you have done your POST request. It then display, what servlet was invoked to handle that request.

Jörg

Avatar

Administrator

Hi 

To learn about how to add/Integrate Jquery into Adobe AEM, read following:-

Link:-https://helpx.adobe.com/experience-manager/using/integrating-jquery-framework-cq.html

//

To add the JQuery framework, add a new node named clientlibs to your component (as discussed below). Add two properties to this node as shown in the following table.

                
NameTypeValue
dependenciesString[]cq.jquery
categoriesString[]jquerysamples

The dependencies property informs CQ to make sure that the JQuery libraries are included in the page. The categories property informs CQ which clientlibs must be included with the JSP that is generated.

To add the JQuery framework to the component, perform these tasks:

  1. Right-click /apps/jqueryapp/components then select New, Node.
  2. Make sure the node type is cq:ClientLibraryFolder and name the node clientlibs.
  3. Right click on clientlibs and select Properties.Add the two properties specified in the previous table to the node. 
  4. On your file system, navigate to the js folder where the JQeury JS file is located. Drag and drop the jquery-1.6.3.min.js (or the version you have) to the clientlibs node by using CRXDE.
  5. Add a TXT file to the clientlibs node named js.txt. The contents of the js.txt file is the file name of the javascript file to include with your component. In this development article, the JS file is jquery-1.6.3.min.js.

 

Link:- https://helpx.adobe.com/in/experience-manager/using/custom-carousel-components.html

 

Thanks and Regards

Kautuk Sahni



Kautuk Sahni

Avatar

Correct answer by
Level 4

Thank you for your responses.  For the benefit of anyone else who wants a "simple" set of instructions how to create a POST request handler for AEM 6.2, here goes :-

1.  Install Maven and install Eclipse IDE for Java EE Developers

2.  Run the following Maven command to create the Java project in the current directory, and input properties when prompted :-

     mvn archetype:generate -DarchetypeGroupId=com.day.jcr.vault -DarchetypeArtifactId=multimodule-content-package-archetype -DarchetypeVersion=1.0.2 -DarchetypeRepository=adobe-public-releases

     groupId:  org.mytest
     artifactId:  mytest
     version:  1.0-SNAPSHOT
     package:  org.mytest
     appsFolderName:  myproject
     artifactName:  My Project
     cqVersion:  6.2
     packageGroup:  My Company

3.  From inside the mytest directory, run the following Maven command :-

     mvn eclipse:eclipse

4.  From Eclipse, goto File menu —-> Import —-> Existing Maven projects —-> mytest directory  ,  and ignore error during import

5.  Create a new Maven Build Run Configuration for the mytest-bundle directory (goals “clean install”) and test it builds JAR in bundle/target directory

6.  In Eclipse Package Explorer, in mytest-bundle, navigate to org.mytest package and add a new class SimplePostHandler  (JAVA CODE BELOW)

7.  Re-build mytest-bundle and check JAR in bundle/target directory has updated

8.  Navigate to http://localhost:4502/system/console/bundles

9.  Click Install/Update button , tick Start Bundle , and click Browse to select your JAR in bundle/target

10.  To test, run the following Curl command and check you get the expected response from your SimplePostHandler :-

      curl --user admin:admin -X POST --data "from=HELLO&to=WORLD" http://localhost:4502/bin/myPostHandler


Below is the Java code needed for step 6 :-


import org.apache.felix.scr.annotations.sling.SlingServlet;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;

@SlingServlet(paths="/bin/myPostHandler", methods="POST", metatype=true)
public class SimplePostHandler extends SlingAllMethodsServlet
{
    @Override
    protected void doPost(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
    {
        try
        {
            final String from = request.getParameter("from");
            final String to = request.getParameter("to");
            
            response.getWriter().write("Version 1.1 , from " + from + " to " + to + "\n");
        }
        catch (final Exception e)
        {
            e.printStackTrace();
        }
    }
}