29 July 2012

Programmatic servlet configuration

Servlet 3 allows you to configure your webapplication in Java.
A set of methods have been added to ServletContext to support this, e.g.

  • addFilter
  • addListener
  • addServlet
When your application starts, you can call these methods from a  ServletContextListener:
@WebListener
public class MyServletContextListener implements ServletContextListener {
  public void contextInitialized(ServletContextEvent event) {
    ServletContext ctx = event.getServletContext();
    ServletRegistration servlet = ctx.addServlet ("ProServlet","org.edu.ProServlet");   
    servlet.addMapping("/dyna/*");
  }
  public void contextDestroyed(ServletContextEvent event) {}
}
After the ServletContext is initialised, you can't call these methods anymore.