Expand my Community achievements bar.

How to call a servlet from react component

Avatar

Level 3

 

 

Hi,

do you have any tutorial on how to create servlet and call it from react?

 

I did this, I create one servlet like that

foalowaini_0-1646725571372.png

and I call it in react like that

foalowaini_1-1646725623291.png

 

and I got this error in console

foalowaini_2-1646725663488.png

 

 

How can I solve it?

 

17 Replies

Avatar

Community Advisor

I hope you're trying to call the servlet from AEM itself, did you try by removing localhost:4502 and just use something like post('/bin/login', fromData) and see how it works.

 

 

 

Avatar

Level 3

 

I tried to change it to get method, it works fine

 

any idea way post not work?

Avatar

Community Advisor

You can try steps as mentioned by @Anmol_Bhardwaj 

Also for more details:

If you are testing from an HTTP Client such as postman, you will need to configure the "Apache Sling Referrer Filter" and "Adobe Granite CSRF Filter". Otherwise, if your AEM page is making an HTTP Post request, it should be working as expected with only the "Apache Sling Referrer Filter" configured without the CSRF Filter. 

Ref: https://sourcedcode.com/blog/video-tutorial/how-to-make-simple-http-post-methods-in-aem-with-a-http-...

Avatar

Community Advisor

Can you try this and see if it works:

If your requests are getting blocked, this should fix it.

 

- Please check if you have implemented SlingHttpSafeServlet or AllMethodServlet in your servlet.

- Try to call the same servlet through Postman and see if it is working fine

 

Avatar

Community Advisor

So you're getting the same error in Postman, after allowing empty in the Sling?
The filter code looks good, but what about the servlet code? Is it implementing SlingAllMethodServlet?

 

Also, if the request doesn't get blocked, even if the servlet doesn't have a doPost method, it is not blocked, rather it just does nothing and sends 200.

 

So, I'm guessing the issue lies with blocking of the request.

Try to first send the request and get a 200 through Postman. This should help you get better clarity on the underlying issue.

Avatar

Level 3

yes I tried on Postman and I got same

Here is the response from Postman

################################################################

################################################################

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>

<head>
    <title>405 Method POST not supported</title>
</head>

<body>
    <h1>Method POST not supported</h1>
    <p>Cannot serve request to /bin/login in com.day.cq.auth.impl.LoginServlet</p>

    <h3>Request Progress:</h3>
    <pre>
      0 TIMER_START{Request Processing}
      1 COMMENT timer_end format is {&lt;elapsed microseconds&gt;,&lt;timer name&gt;} &lt;optional message&gt;
     44 LOG Method=POST, PathInfo=null
     45 TIMER_START{handleSecurity}
   1813 TIMER_END{1765,handleSecurity} authenticator org.apache.sling.auth.core.impl.SlingAuthenticator@296f089d returns true
   2156 TIMER_START{ResourceResolution}
   2230 TIMER_END{73,ResourceResolution} URI=/bin/login resolves to Resource=ServletResource, servlet=com.day.cq.auth.impl.LoginServlet, path=/bin/login
   2282 LOG Resource Path Info: SlingRequestPathInfo: path=&apos;/bin/login&apos;, selectorString=&apos;null&apos;, extension=&apos;null&apos;, suffix=&apos;null&apos;
   2282 TIMER_START{ServletResolution}
   2284 TIMER_START{resolveServlet(/bin/login)}
   2292 TIMER_END{7,resolveServlet(/bin/login)} Using servlet com.day.cq.auth.impl.LoginServlet
   2294 TIMER_END{11,ServletResolution} URI=/bin/login handled by Servlet=com.day.cq.auth.impl.LoginServlet
   2297 LOG Applying Requestfilters
   2299 LOG Calling filter: com.adobe.granite.resourceresolverhelper.impl.ResourceResolverHelperImpl
   2304 LOG Calling filter: org.apache.sling.security.impl.ContentDispositionFilter
   2307 LOG Calling filter: org.apache.sling.i18n.impl.I18NFilter
   2310 LOG Calling filter: com.adobe.granite.httpcache.impl.InnerCacheFilter
   2314 LOG Calling filter: org.apache.sling.rewriter.impl.RewriterFilter
   2316 LOG Calling filter: com.adobe.cq.mcm.campaign.servlets.CampaignCopyTracker
   2318 LOG Calling filter: com.adobe.cq.history.impl.HistoryRequestFilter
   2467 LOG Calling filter: com.day.cq.wcm.core.impl.WCMRequestFilter
   2477 LOG Calling filter: com.adobe.cq.wcm.core.components.internal.servlets.CoreFormHandlingServlet
   2480 LOG Calling filter: com.adobe.granite.optout.impl.OptOutFilter
   2484 LOG Calling filter: com.day.cq.wcm.foundation.forms.impl.FormsHandlingServlet
   2485 LOG Calling filter: com.adobe.cq.social.commons.cors.CORSAuthenticationFilter
   2487 LOG Calling filter: org.apache.sling.engine.impl.debug.RequestProgressTrackerLogFilter
   2489 LOG Calling filter: com.aem.core.filters.LoggingFilter
   2492 LOG Calling filter: com.aem.geeks.core.filters.LoggingFilter
   2495 LOG Calling filter: com.day.cq.wcm.mobile.core.impl.redirect.RedirectFilter
   2498 LOG Calling filter: com.day.cq.wcm.core.impl.AuthoringUIModeServiceImpl
   2581 LOG Calling filter: com.adobe.granite.csrf.impl.CSRFFilter
   2584 LOG Calling filter: com.adobe.granite.rest.assets.impl.AssetContentDispositionFilter
   2586 LOG Calling filter: com.adobe.granite.requests.logging.impl.RequestLoggerImpl
   2590 LOG Calling filter: com.adobe.granite.rest.impl.servlet.ApiResourceFilter
   2613 LOG Calling filter: com.day.cq.dam.core.impl.assetlinkshare.AdhocAssetShareAuthHandler
   2615 LOG Calling filter: com.day.cq.dam.core.impl.servlet.ActivityRecordHandler
   2627 LOG Calling filter: com.adobe.cq.social.ugcbase.security.impl.SaferSlingPostServlet
   2631 LOG Calling filter: com.day.cq.wcm.core.impl.warp.TimeWarpFilter
   2637 LOG Applying Componentfilters
   2638 LOG Calling filter: com.day.cq.personalization.impl.TargetComponentFilter
   2640 LOG Calling filter: com.day.cq.wcm.core.impl.page.PageLockFilter
   2643 LOG Calling filter: com.day.cq.wcm.core.impl.WCMComponentFilter
   2777 LOG Calling filter: com.day.cq.wcm.core.impl.WCMDebugFilter
   2784 TIMER_START{com.day.cq.auth.impl.LoginServlet#0}
   2816 LOG Applying Error filters
   2817 LOG Calling filter: org.apache.sling.i18n.impl.I18NFilter
   2819 LOG Calling filter: org.apache.sling.rewriter.impl.RewriterFilter
   2824 TIMER_START{handleError:status=405}
   3677 TIMER_END{849,handleError:status=405} Using handler /libs/sling/servlet/errorhandler/default.jsp
   5203 LOG Found processor for post processing ProcessorConfiguration: {contentTypes=[text/html], order=-1, active=true, valid=true, processErrorResponse=true, pipeline=(generator=Config(type=htmlparser, config={}), transformers=(Config(type=linkchecker, config={}), Config(type=mobile, config=JcrPropertyMap [node=Node[NodeDelegate{tree=/libs/cq/config/rewriter/default/transformer-mobile: { jcr:primaryType = nt:unstructured, component-optional = true}}], values={jcr:primaryType=nt:unstructured, component-optional=true}]), Config(type=mobiledebug, config=JcrPropertyMap [node=Node[NodeDelegate{tree=/libs/cq/config/rewriter/default/transformer-mobiledebug: { jcr:primaryType = nt:unstructured, component-optional = true}}], values={jcr:primaryType=nt:unstructured, component-optional=true}]), Config(type=contentsync, config=JcrPropertyMap [node=Node[NodeDelegate{tree=/libs/cq/config/rewriter/default/transformer-contentsync: { jcr:primaryType = nt:unstructured, component-optional = true}}], values={jcr:primaryType=nt:unstructured, component-optional=true}]), serializer=Config(type=htmlwriter, config={}))}
   5515 TIMER_END{5513,Request Processing} Dumping SlingRequestProgressTracker Entries
</pre>


    <hr>
    <address>ApacheSling/2.6 (jetty/9.4.15.v20190215, Java HotSpot(TM) 64-Bit Server VM 1.8.0_321, Windows 10 10.0
        amd64)</address>
</body>

</html>
#########################################################
#########################################################
 
 
 
Here is servlet code:
###########################################################
##########################################################
package com.myproject.aem.core.servlets;

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

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;

import javax.servlet.ServletException;
import java.io.IOException;

@Component(
  service = Servlet.class,
  property = {
    Constants.SERVICE_DESCRIPTION + "=Simple Demo Servlet",
    "sling.servlet.methods=" + HttpConstants.METHOD_POST,
    "sling.servlet.paths=" + "/bin/login" })
public class LoginServlet extends SlingAllMethodsServlet {

  /**
   * Generated serialVersionUID
   */
  private static final long serialVersionUID = -159625176093879129L;
 
  /**
   * Logger
   */
  private static final Logger log = LoggerFactory.getLogger(LoginServlet.class);
 

    // @Override
    // protected void doGet(final SlingHttpServletRequest req,
    //         final SlingHttpServletResponse resp)  {
    //     // final Resource resource = req.getResource();
    //    resp.setStatus(HttpServletResponse.SC_OK);

    //     // resp.setContentType("text/plain");
    //     // resp.getWriter().write("Title = " + resource.getValueMap().get(JcrConstants.JCR_TITLE));
    // }

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

    /**
     * Getting the instance of resource resolver from the request
     */
    ResourceResolver resourceResolver = request.getResourceResolver();
   
    /**
     * Getting the resource object via path
     */
    Resource resource = resourceResolver.getResource("/content/myproject/en");

    log.info("Resource is at path {}", resource.getPath());
    if(request.getAttribute("username").equals("DEV_PRAVEENK"))
      response.setStatus(HttpServletResponse.SC_OK);
    else
      response.setStatus(HttpServletResponse.SC_FORBIDDEN);
  }
}
######################################################
######################################################

Avatar

Community Advisor

@foalowaini 

The request to /bin/login is served using OOTB servlet and not your custom servlet. 

 

2294 TIMER_END{11,ServletResolution} URI=/bin/login handled by Servlet=com.day.cq.auth.impl.LoginServlet

 

com.day.cq.auth.impl.LoginServlet - OOTB servlet registered with path - /bin/login and it overrides GET method alone and hence the error, POST is not allowed (405)

Suggest to change the path specific to your project (say, /bin/exampleproject/login) or register the servlet with resourceType

Avatar

Level 3

Hi,

 

I tried your change, but still not work

it give me 500 (server error)

 

and in postman a message unable to create node at /bin/my

 

#################################################

######### Logs from Adobe Console ##################

#################################################

0 TIMER_START{Request Processing}
6 COMMENT timer_end format is {<elapsed microseconds>,<timer name>} <optional message>
17 LOG Method=POST, PathInfo=null
21 TIMER_START{handleSecurity}
2725 TIMER_END{2701,handleSecurity} authenticator org.apache.sling.auth.core.impl.SlingAuthenticator@1c918f96 returns true
3293 TIMER_START{ResourceResolution}
3581 TIMER_END{285,ResourceResolution} URI=/bin/my/login resolves to Resource=NonExistingResource, path=/bin/my/login
3597 LOG Resource Path Info: SlingRequestPathInfo: path='/bin/my/login', selectorString='null', extension='null', suffix='null'
3598 TIMER_START{ServletResolution}
3605 TIMER_START{resolveServlet(/bin/my/login)}
5260 LOG {0}: no servlet found
5278 TIMER_END{1669,resolveServlet(/bin/my/login)} Using servlet org.apache.sling.servlets.post.impl.SlingPostServlet
5289 TIMER_END{1689,ServletResolution} URI=/bin/my/login handled by Servlet=org.apache.sling.servlets.post.impl.SlingPostServlet
5300 LOG Applying Requestfilters
5310 LOG Calling filter: com.adobe.granite.resourceresolverhelper.impl.ResourceResolverHelperImpl
5324 LOG Calling filter: org.apache.sling.security.impl.ContentDispositionFilter
5332 LOG Calling filter: org.apache.sling.i18n.impl.I18NFilter
5338 LOG Calling filter: com.adobe.granite.httpcache.impl.InnerCacheFilter
5355 LOG Calling filter: org.apache.sling.rewriter.impl.RewriterFilter
5360 LOG Calling filter: com.adobe.cq.mcm.campaign.servlets.CampaignCopyTracker
5367 LOG Calling filter: com.adobe.cq.history.impl.HistoryRequestFilter
5723 LOG Calling filter: com.day.cq.wcm.core.impl.WCMRequestFilter
5744 LOG Calling filter: com.adobe.cq.wcm.core.components.internal.servlets.CoreFormHandlingServlet
5754 LOG Calling filter: com.adobe.granite.optout.impl.OptOutFilter
5763 LOG Calling filter: com.day.cq.wcm.foundation.forms.impl.FormsHandlingServlet
5768 LOG Calling filter: com.adobe.cq.social.commons.cors.CORSAuthenticationFilter
5774 LOG Calling filter: org.apache.sling.engine.impl.debug.RequestProgressTrackerLogFilter
5778 LOG Calling filter: com.aem.core.filters.LoggingFilter
5786 LOG Calling filter: com.aem.geeks.core.filters.LoggingFilter
5792 LOG Calling filter: com.day.cq.wcm.mobile.core.impl.redirect.RedirectFilter
5798 LOG Calling filter: com.day.cq.wcm.core.impl.AuthoringUIModeServiceImpl
5984 LOG Calling filter: com.adobe.granite.csrf.impl.CSRFFilter
5993 LOG Calling filter: com.adobe.granite.rest.assets.impl.AssetContentDispositionFilter
5998 LOG Calling filter: com.adobe.granite.requests.logging.impl.RequestLoggerImpl
6010 LOG Calling filter: com.adobe.granite.rest.impl.servlet.ApiResourceFilter
6059 LOG Calling filter: com.day.cq.dam.core.impl.assetlinkshare.AdhocAssetShareAuthHandler
6065 LOG Calling filter: com.day.cq.dam.core.impl.servlet.ActivityRecordHandler
6091 LOG Calling filter: com.adobe.cq.social.ugcbase.security.impl.SaferSlingPostServlet
6101 LOG Calling filter: com.day.cq.wcm.core.impl.warp.TimeWarpFilter
6116 LOG Applying Componentfilters
6119 LOG Calling filter: com.day.cq.personalization.impl.TargetComponentFilter
6123 LOG Calling filter: com.day.cq.wcm.core.impl.page.PageLockFilter
6133 LOG Calling filter: com.day.cq.wcm.core.impl.WCMComponentFilter
6166 LOG Calling filter: com.day.cq.wcm.core.impl.WCMDebugFilter
6185 TIMER_START{org.apache.sling.servlets.post.impl.SlingPostServlet#0}
6314 LOG Calling PostOperation: org.apache.sling.servlets.post.impl.operations.ModifyOperation
10117 TIMER_END{3928,org.apache.sling.servlets.post.impl.SlingPostServlet#0}
10158 LOG Filter timing: filter=com.day.cq.wcm.core.impl.WCMDebugFilter, inner=4, total=4, outer=0
10164 LOG Filter timing: filter=com.day.cq.wcm.core.impl.WCMComponentFilter, inner=4, total=4, outer=0
10167 LOG Filter timing: filter=com.day.cq.wcm.core.impl.page.PageLockFilter, inner=4, total=4, outer=0
10177 TIMER_END{10176,Request Processing} Request Processing
10186 LOG Filter timing: filter=com.adobe.cq.dtm.reactor.impl.servlets.ClientLibraryFilter, inner=0, total=4, outer=4
10189 LOG Filter timing: filter=com.adobe.cq.dam.webdav.impl.io.DamWebdavRequestFilter, inner=4, total=4, outer=0
10192 LOG Filter timing: filter=com.day.cq.wcm.core.impl.warp.TimeWarpFilter, inner=4, total=4, outer=0
10194 LOG Filter timing: filter=com.adobe.cq.social.ugcbase.security.impl.SaferSlingPostServlet, inner=4, total=4, outer=0
10197 LOG Filter timing: filter=com.adobe.cq.dtm.impl.servlets.DTMLibraryCompatibilityFilter, inner=4, total=4, outer=0
10200 LOG Filter timing: filter=com.day.cq.dam.core.impl.servlet.DamContentDispositionFilter, inner=4, total=4, outer=0
10202 LOG Filter timing: filter=com.day.cq.dam.core.impl.servlet.ActivityRecordHandler, inner=4, total=4, outer=0
10205 LOG Filter timing: filter=com.day.cq.dam.core.impl.assetlinkshare.AdhocAssetShareAuthHandler, inner=4, total=4, outer=0
10208 LOG Filter timing: filter=com.adobe.granite.rest.impl.servlet.ApiResourceFilter, inner=4, total=4, outer=0
10210 LOG Filter timing: filter=com.adobe.granite.requests.logging.impl.RequestLoggerImpl, inner=4, total=4, outer=0
10213 LOG Filter timing: filter=com.adobe.granite.rest.assets.impl.AssetContentDispositionFilter, inner=4, total=4, outer=0
10215 LOG Filter timing: filter=com.adobe.granite.csrf.impl.CSRFFilter, inner=4, total=4, outer=0
10218 LOG Filter timing: filter=com.day.cq.wcm.core.impl.AuthoringUIModeServiceImpl, inner=4, total=4, outer=0
10220 LOG Filter timing: filter=com.day.cq.wcm.mobile.core.impl.redirect.RedirectFilter, inner=4, total=4, outer=0
10223 LOG Filter timing: filter=com.aem.geeks.core.filters.LoggingFilter, inner=4, total=4, outer=0
10226 LOG Filter timing: filter=com.aem.core.filters.LoggingFilter, inner=4, total=4, outer=0
10228 LOG Filter timing: filter=org.apache.sling.engine.impl.debug.RequestProgressTrackerLogFilter, inner=4, total=4, outer=0
10231 LOG Filter timing: filter=com.adobe.cq.social.commons.cors.CORSAuthenticationFilter, inner=4, total=4, outer=0
10233 LOG Filter timing: filter=com.day.cq.wcm.foundation.forms.impl.FormsHandlingServlet, inner=4, total=4, outer=0
10235 LOG Filter timing: filter=com.adobe.granite.optout.impl.OptOutFilter, inner=4, total=4, outer=0
10238 LOG Filter timing: filter=com.adobe.cq.wcm.core.components.internal.servlets.CoreFormHandlingServlet, inner=4, total=4, outer=0
10241 LOG Filter timing: filter=com.day.cq.wcm.core.impl.WCMRequestFilter, inner=4, total=4, outer=0
10243 LOG Filter timing: filter=com.adobe.cq.history.impl.HistoryRequestFilter, inner=4, total=5, outer=1
10246 LOG Filter timing: filter=com.adobe.cq.mcm.campaign.servlets.CampaignCopyTracker, inner=5, total=5, outer=0
10248 LOG Filter timing: filter=org.apache.sling.rewriter.impl.RewriterFilter, inner=5, total=5, outer=0
10250 LOG Filter timing: filter=com.adobe.granite.httpcache.impl.InnerCacheFilter, inner=5, total=5, outer=0
10253 LOG Filter timing: filter=org.apache.sling.i18n.impl.I18NFilter, inner=5, total=5, outer=0
10255 LOG Filter timing: filter=org.apache.sling.security.impl.ContentDispositionFilter, inner=5, total=5, outer=0
10258 LOG Filter timing: filter=org.apache.sling.distribution.servlet.DistributionAgentCreationFilter, inner=5, total=5, outer=0

Avatar

Community Advisor

Looks like your servlet is not available in the instance at first place.

3581 TIMER_END{285,ResourceResolution} URI=/bin/my/login resolves to Resource=NonExistingResource, path=/bin/my/login
3597 LOG Resource Path Info: SlingRequestPathInfo: path='/bin/my/login', selectorString='null', extension='null', suffix='null'
3598 TIMER_START{ServletResolution}
3605 TIMER_START{resolveServlet(/bin/my/login)}
5260 LOG {0}: no servlet found

 Cross check the deployment and see if you are able to see the servlet in 

http://localhost:4502/system/console/components and is active

or

http://localhost:4502/system/console/servletresolver Enter the servlet path and choose the method to be POST and see if it resolves to your servlet. 

Avatar

Community Advisor

This means your bundle (that contains the servlet code) is not deployed to the AEM instance. 

How are you deploying your code ?

 

Avatar

Community Advisor

Since it is your local instance, delete the bundle manually from this path - /apps/yourproject/install/yourproject.core-0.0.1-SNAPSHOT.jar in CRXDE and then trigger the deployment again. 

(Provided core module is enabled and bundle is getting created successfully as part of the build process)

Avatar

Level 3

I tried that not solved.

 

I found the below error on bundle console

foalowaini_0-1647030866126.png

and the project in install state not active

 

Avatar

Level 1

Just dealing with the same error here, I came around this article that may be helpful: