How to read servlet response in Sling Model | Community
Skip to main content
Level 3
April 5, 2022

How to read servlet response in Sling Model

  • April 5, 2022
  • 3 replies
  • 3294 views

I've a servlet written in AEM using Sling ResourceTypes which returns some response. 

 

And the path  http://localhostL4502/content/example/testpage.productsjson.html is giving the servlet response when I hit through browser. Now I would like to read the same json response in sling Model. How can I call the servlet in sling model. Any example code snippet will be helpful. 

 

sample servlet: 

@Component(service=Servlet.class,
property={
Constants.SERVICE_DESCRIPTION + "=Simple Demo Servlet",
"sling.servlet.methods=" + HttpConstants.METHOD_GET,
"sling.servlet.resourceTypes="+ "exampe/components/structure/page",
"sling.servlet.extensions=" + "productsjson",
})
public class SampleServlet extends SlingSafeMethodsServlet {
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)throws IOException
{
response.getWriter().write("Welcome to the Products Servlet!");
}
}

 

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

3 replies

milind_bachani
Adobe Employee
Adobe Employee
April 5, 2022

Hi @sonur1 ,

 

Please refer to @lukasz-m 's answer on thread : https://experienceleaguecommunities.adobe.com/t5/adobe-experience-manager/call-a-servlet-get-request-from-sling-model/m-p/437167

 

This will answer your query, since its not a good approach to call a servlet from model. 

Thanks.

SonuR1Author
Level 3
April 6, 2022

@milind_bachani , the thread explains the other way around where we can call service from servlet. I would like to know how can use call the servlet in service at least. Any example code snippets will be helpful.

 

 

Anmol_Bhardwaj
Community Advisor
Community Advisor
April 6, 2022

Hi @sonur1 ,

 

Sling Modals are just java classes, so you would need to call your servlet the same way we make any HttpRequest in Java, and then you can traverse through the response.

 

Reference: https://www.baeldung.com/java-http-request

 

joerghoh
Adobe Employee
Adobe Employee
April 6, 2022

You should move the functionality out of the servlet into a re-usable service. Then both the servlet and the model can call this service.

 

(Chaining servlets is possible, but I due to the complexity of request handling more complicated than just refactoring the code.)