Heena Shirke
How to create a sling servlet with dynamic path
I recently worked upon a use-case where I had to register a sling servlet with dynamic paths, and following is how I implemented it:
To designate an ObjectClassDefinition to the Servlet which on save of the configuration, sets the servlet.servlets.paths property of the servlet.
@Component(service = Servlet.class)
@Designate(ocd = DynamicallyRegisteredServlet.Config.class)
public class DynamicallyRegisteredServlet extends SlingSafeMethodsServlet {
private static final long serialVersionUID = 1L;
@ObjectClassDefinition(name = "DynamicallyRegisteredServlet",
description = "Servlet Path to register this Servlet")
public static @interface Config {
@AttributeDefinition(name = "Servlet Paths",
description = "sling.servlet.paths Property")
String[] sling_servlet_paths() default { "/bin/aemblog/thisworks",
"/bin/aemblog/thistoo" };
}
@Override
protected void doGet(final SlingHttpServletRequest req,
final SlingHttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write("Servlet Found");
}
}
Let's navigate to http://localhost:4502/system/console/configMgr, and checkout the configuration created. All the paths entered in this field can now be used to trigger DynamicallyRegisteredServlet

So, let's trying hitting http://localhost:4502/bin/aemblog/thisworks and http://localhost:4502/bin/aemblog/thistoo.


And that worked!
That's all for today! Remember to hit the like icon! It keeps me motivated.🥹