How to call a servlet from react component | Community
Skip to main content
Level 2
March 8, 2022

How to call a servlet from react component

  • March 8, 2022
  • 3 replies
  • 8108 views

 

 

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

and I call it in react like that

 

and I got this error in console

 

 

How can I solve it?

 

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.

3 replies

Siva_Sogalapalli
Community Advisor
Community Advisor
March 8, 2022

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.

 

 

 

Level 2
March 8, 2022
Anmol_Bhardwaj
Community Advisor
Community Advisor
March 8, 2022

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

 

Level 2
March 8, 2022

@anmol_bhardwaj 

 

I tried that, does not works

 

I have this as filter

 

Vijayalakshmi_S
Level 10
March 8, 2022

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);
 

    // @9944223
    // 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);
  }
}
######################################################
######################################################

@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

Flores-Lucas
June 20, 2023

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