I need to map a servlet in runtime. Is there anyway of doing it? I saw a method called addServlet
in servletContext
Interface. But I couldn't find a way to access it.

- 2,389
- 1
- 16
- 28
-
Have a look at (MVC) front controller pattern. This way you can just end up with a single servlet. There are frameworks for this (JSF, Struts, SpringMVC, Wicket, Stripes, Play, etc). In depth explanation of the working can be found here: [design patterns web based applications](http://stackoverflow.com/questions/3541077/design-patterns-web-based-applications/). – BalusC Sep 24 '11 at 18:24
2 Answers
You can dynamically add servlets at runtime in Servlet 3.0. As you found, you do need access to the ServletContext
in order to do this. The ServletContext
is available from most web components, such as servlets or listeners. I'm not sure your use case for doing this, but here are a couple examples where you may access the ServletContext in order to add web components at runtime -
public class MyServlet extends HttpServlet {
public void init(ServletConfig config) throws ServletException {
config.getServletContext().addServlet(...);
}
. . .
}
public class MyListener implements ServletContextListener {
public void contextDestroyed(ServletContextEvent sce) {
sce.getServletContext().addServlet(...);
}
public void contextInitialized(ServletContextEvent sce) {}
}

- 7,206
- 4
- 36
- 63
-
thanks, this is what i was looking for. is there any method of doing it without `servlet 3.0`? – tiran Sep 28 '11 at 15:50
-
There is no equivalent prior to Servlet 3.0. It's possible that there _may_ be some container-proprietary approaches, however. IIRC, Jetty may have allowed dynamic servlet registration before Servlet 3.0. – shelley Sep 28 '11 at 16:58
I think the only way to do this would be to use a filter, and then based on the request URL, load the servlet and call directly into it, as opposed to using the chain.doFilter(req, resp);
If you have an authentication filter; make sure to add this new filter lower on the web.xml so you don't accidentally forget to authenticate!
There is a library which could help you with this here: http://code.google.com/p/urlrewritefilter/
This filter works basically as I have described.
To be honest though; I think you should re-assess why you're doing this in the first place. You likely don't need to do this and if you think about it you can probably find a way around whatever problem you're having using the good 'ole static servlet-mappings in your web.xml. That decision is yours to make though.

- 6,141
- 2
- 38
- 65