3.11.4. Registration of Servlets and Filters

Servlets and filters defined in an application component have to be registered programmatically. Usually, servlets and filters are registered in the web.xml configuration file, however, the component’s web.xml has no effect in the target application.

The ServletRegistrationManager bean is designed for registering servlets and filters dynamically with the correct ClassLoader and enables using such static classes as AppContext. It also guarantees the correct work for all deployment options.

ServletRegistrationManager has two methods:

  1. createServlet() - creates a servlet of the given servlet class. It loads the servlet class with the correct ClassLoader that is obtained from the application context object. It means that a new servlet will be able to use static classes, for example, AppContext or Messages bean.

  2. createFilter() - creates filters in the same way.

In order to use this bean, we recommend creating an initializer bean in the application component. This bean should contain event listeners that are subscribed to ServletContextInitializedEvent and ServletContextDestroyedEvent.

For example:

@Component
public class WebInitializer {

    @Inject
    private ServletRegistrationManager servletRegistrationManager;

    @EventListener
    public void initializeHttpServlet(ServletContextInitializedEvent e) {
        Servlet myServlet = servletRegistrationManager.createServlet(
                e.getApplicationContext(), "com.demo.comp.MyHttpServlet");

        e.getSource().addServlet("my_servlet", myServlet)
                .addMapping("/myservlet/");
    }
}

Here, the WebInitializer class has only one event listener which is used to register an HTTP servlet from an application component in the target application.

The createServlet() method takes the application context obtained from ServletContextInitializedEvent and the HTTP servlet FQN. Then we register the servlet by its name (my_servlet) and define HTTP-mapping (/myservlet/). Now, if you add this app component to you application, MyHttpServlet will be registered right after the initialization of the servlet and application contexts.

If the application context is /app, and servlet is registered with mapping myservlet, it will be available at /app/myservlet.

For more complex example, see the Registering DispatcherServlet from Application Component section.