0

I have written a Email Exchange service in my local and deployed it as a bundle into AEM6.So my service is available now as an sling service.

I have consumed it in my jsp as follows.

EmailService es - sling.getService(EmailService.class);

But now in Aem6 I need to call the service in sightly on a button click which will be done using an ajax call.

Can you please let me know how I can consume an sling service on an ajax call.

Thanks, Esha

Esha Ch
  • 13
  • 1
  • 5

2 Answers2

2

You may not be able to call your service directly via AJAX since your service doesn't cater to requests.

You can write a SlingServlet that resolves to a path / resourceType which can Reference your EmailExchange service, or access any content node whose script uses your EmailExchange service via sling.getService()

@SlingServlet(paths="/bin/emailexchange.servlet", methods="POST")
public Class EmailExchangeServlet extends SlingAllMethodsServlet {

    @Reference
    private EmailService emailService;

    protected void doPost(SlingHttpServletRequest req, SlingHttpServletResponse res) {
        // do your stuff 
    }
}
rakhi4110
  • 9,253
  • 2
  • 30
  • 49
0

To keep separation of concerns:

  • Services provide data/implementations inside of the application server (also happen to be testable at build time outside of AEM/CQ5). These should provide business logic/rules, but generally avoid rendering implementation.
  • Servlets respond to HTTP requests, and ideally wrap a call to a service, to keep their code clean. The servlet can determine if the response needs to be JSON, HTML, XML or other
  • Components JSP's (and Sightly) should generally act as a template for the response. They can also call Services directly to perform business logic.
  • AJAX is an HTTP request that can interact with the path of either a servlet or a component to get the (typically) JSON or HTML response.

In this light, your AJAX should POST to a Servlet, which can call the Service.

IT Gumby
  • 1,067
  • 8
  • 11