Programmatic servlet registration¶
Programmatic servlet registration is a mechanism introduced in Servlet 3.0 that allows frameworks and applications to register servlets, filters, and listeners programmatically, rather than relying solely on the web.xml deployment descriptor.^[600-developer-java-spring-servletcontainerinitializer.md]
This process is facilitated by the ServletContext object, which provides methods to dynamically add components to the web application during startup.
Mechanism¶
The primary mechanism for enabling this functionality is the ServletContainerInitializer interface.^[600-developer-java-spring-servletcontainerinitializer.md] It is invoked by the web container at startup, providing third-party frameworks (like Spring) with an opportunity to register their components, such as DispatcherServlet, before the application fully starts.^[600-developer-java-spring-servletcontainerinitializer.md]
Implementation Requirements¶
To use a ServletContainerInitializer, the following requirements must be met:^[600-developer-java-spring-servletcontainerinitializer.md]
- Service Provider Configuration: A file named
javax.servlet.ServletContainerInitializermust be created in theMETA-INF/services/directory of the JAR file. - Class Declaration: This file must contain the fully qualified name of the implementation class (e.g.,
org.springframework.web.WebApplicationInitializer).^[600-developer-java-spring-servletcontainerinitializer.md]
Interface Signature¶
The interface defines a single method that the container calls:
java
public interface [ServletContainerInitializer](<./servletcontainerinitializer.md>) {
void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException;
}^[600-developer-java-spring-servletcontainerinitializer.md]
Spring Framework Integration¶
The Spring Framework utilizes this mechanism through the SpringServletContainerInitializer class, which implements ServletContainerInitializer.^[600-developer-java-spring-servletcontainerinitializer.md] This class acts as a bootstrap for Spring's code-based configuration, allowing the application to start without a web.xml file.
It leverages the @HandlesTypes annotation to identify specific classes of interest (such as WebApplicationInitializer implementations) and passes them to the onStartup method.^[600-developer-java-spring-servletcontainerinitializer.md]
Related Concepts¶
- Spring Framework
- [[Servlet]]
Sources¶
^[600-developer-java-spring-servletcontainerinitializer.md]