top of page
  • Writer's pictureHeena

How to create a sling servlet with dynamic path

Updated: Dec 12, 2023

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

DynamicallyRegisteredServlet Configuration

Servlet Response

Servlet Response

And that worked!

That's all for today! If you've found this blog post informative or helpful, I’d greatly appreciate it if you could give it a like. It keeps me motivated 💛


Related Posts

See All
bottom of page