One can add / register servlet or filters dynamically at context initialization time . ServletContext has methods to register is dynamically.
ServletRegistration.Dynamic | addServlet(java.lang.String servletName,
java.lang.Class < ? extends Servlet > servletClass )
Adds the servlet with the given name and class type to this servlet context. |
ServletRegistration.Dynamic | addServlet(java.lang.String servletName,
Servlet servlet)
Registers the given servlet instance with this ServletContext under the given servletName. |
ServletRegistration.Dynamic | addServlet(java.lang.String servletName, java.lang.String className) |
Below is an example
MyCtxInitializer extends ServletcontextInitializer {
void contextInitialized(
ServletContextEvent sce
)
{
ServletContext ctx = sce.getServletContext();
ServletRegistration.Dynamic dyna =
sce.addServlet("newServlet " , NewServlet.class);
//NewServlet must be a servlet class extending Servlet
dyna.addMapping("/OneServlet"); // map to URL Pattern
try{
Servlet xyz = ctx.createServlet (SecondServlet.class);
dyna.addServlet("secondServlet",xyz);
dyna.addMapping("/TwoServlet");
}catch(Exception ex) {}
}
void contextDestroyed(
ServletContextEvent sce
){ }
}
Similarly for Filter and Listener .
No comments:
Post a Comment