top of page
Writer's pictureHeena

How to create a sling servlet with dynamic path

Updated: May 2


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



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 💛


Enjoying my ad-free blog? Support by buying me a coffee! I've kept this space ad-free, sponsoring it myself to maintain its purity. Your contribution would help keep the site afloat and ensure quality content. Thanks for being part of this ad-free community.

704 views

Related Posts

See All

© 2023 aem-blog by Heena Shirke

bottom of page