Highlighted

Register Sling Servlet or Any Service Dynamically in AEM | AEM Community Blog Seeding

Avatar

Avatar

kautuk_sahni

Community Manager

Total Posts

5.6K

Likes

969

Correct Answer

1.1K

Avatar

kautuk_sahni

Community Manager

Total Posts

5.6K

Likes

969

Correct Answer

1.1K
kautuk_sahni
Community Manager

28-10-2020

BlogImage.jpg

Register Sling Servlet or Any Service Dynamically in AEM by Sgaemsolutions

Abstract

While working on a project last week, I went through a very interesting use case and so many learnings while solving that. This blog is shared with you about that learning process I have been through.


Problem Statement: I was working on an integration tool with AEM, in which we are having many servlets registered with paths . Few of the servlets are being called by a third party and few are for internal calls.


All the servlets start with a specific prefix. Let’s suppose: /bin/aem-integration/events, /bin/aem-integration/tasks etc. So the prefix for all the servlets is "/bin/aem-integration" and it was as a constant in the code.


But while using that tool, a client requested to provide them the flexibility to define the prefix as per their requirement. So that, while they made calls from any external system to AEM, they could make their own choice of prefix or may be a very environment specific prefix like for dev it will be /bin/aem-integration/dev/tasks but for stage it will be /bin/aem-integration/stage/tasks. The requirement looks easier but while implementing, it was quite challenging.


How I approach this problem:

So if I mention the above problem precisely, it is registering the servlets based on dynamic paths.


How can we do that?

Let’s suppose I have a servlet "RunModeServlet" using SlingSettings as a Reference and I want to register this servlet dynamically. So how to do that.




import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.apache.sling.settings.SlingSettingsService;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;

import javax.servlet.Servlet;
import java.io.IOException;

@Component(
service = {Servlet.class},
property = {
"sling.servlet.paths=/bin/aem-integration/tasks",
"sling.servlet.paths=/bin/aem-integration/files",
"sling.servlet.extensions=json",
"sling.servlet.methods=GET"
}
)
public class RunModeServlet extends SlingAllMethodsServlet {

@Reference
private SlingSettingsService slingSettingsService;

@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {
response.getWriter().println(this.slingSettingsService.getRunModes().contains("publish"));
}
}

Read Full Blog

Register Sling Servlet or Any Service Dynamically in AEM

Q&A

Please use this thread to ask the related questions.

AEM AEMEBlogSeeding Experience Manager