Your achievements

Level 1

0% to

Level 2

Tip /
Sign in

Sign in to Community

to gain points, level up, and earn exciting badges like the new
Bedrock Mission!

Learn more

View all

Sign in to view all badges

How to read servlet response in Sling Model

Avatar

Level 3

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!");
}
}

 

4 Replies

Avatar

Employee Advisor

Hi @SonuR1 ,

 

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

 

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

Thanks.

Avatar

Level 3

@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.

 

 

Avatar

Community Advisor

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

 

Avatar

Employee Advisor

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