How Can I call a Service in Servlet | Community
Skip to main content
Level 2
March 23, 2021
Solved

How Can I call a Service in Servlet

  • March 23, 2021
  • 4 replies
  • 3844 views

I have created a service called MyService and implemented it, I want to call it in my servlet so how can I do that? please help

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

Hi @ashwinikhaple 

Please see below:

 

public class MyServlet extends SlingAllMethodsServlet {

private static final long serialVersionUID = 1L;

@Reference
private transient MyService myservice;

@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {

myservice.anything();

}
}

 

https://sling.apache.org/documentation/the-sling-engine/servlets.html

 

Hope this helps!
Thanks!

4 replies

Rohit_Utreja
Community Advisor
Community Advisor
March 23, 2021

Hi, @ashwinikhaple,

 

If you are using SCR annotation, you can use @Reference annotation to inject the service into the servlet.

Something similar to this.

@Reference
MyService service;

You can refer to the below thread for more details.

https://stackoverflow.com/questions/56732548/aem-6-4-x-osgi-servlet-how-to-access-an-osgi-service-from-a-servlet

 

 If you are using R6 annotation, Please refer to below URL for the same.

http://www.nateyolles.com/blog/2017/05/osgi-declarative-services-annotations-in-aem

 

Level 2
March 23, 2021

Now, I am trying to render values returned by methods that are in MyService, So to render those in servlet what can I use? 

Below is MyService Methods code

 

public interface MyService
{
public String getMyFirstName();
public String getMyLastName();
public String getMyHobby();
}

Asutosh_Jena_
Community Advisor
Asutosh_Jena_Community AdvisorAccepted solution
Community Advisor
March 23, 2021

Hi @ashwinikhaple 

Please see below:

 

public class MyServlet extends SlingAllMethodsServlet {

private static final long serialVersionUID = 1L;

@Reference
private transient MyService myservice;

@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {

myservice.anything();

}
}

 

https://sling.apache.org/documentation/the-sling-engine/servlets.html

 

Hope this helps!
Thanks!

Bhuwan_B
Community Advisor
Community Advisor
March 23, 2021
Ankur_Khare
Community Advisor
Community Advisor
March 23, 2021

Kindly use like below-

 

@3214626
private transient ApiService apiService;