spring-framework / org.springframework.web

Package org.springframework.web

Types

SpringServletContainerInitializer

open class SpringServletContainerInitializer : ServletContainerInitializer

Servlet 3.0 ServletContainerInitializer designed to support code-based configuration of the servlet container using Spring's WebApplicationInitializer SPI as opposed to (or possibly in combination with) the traditional web.xml-based approach. Mechanism of Operation This class will be loaded and instantiated and have its #onStartup method invoked by any Servlet 3.0-compliant container during container startup assuming that the spring-web module JAR is present on the classpath. This occurs through the JAR Services API ServiceLoader#load(Class) method detecting the spring-web module's META-INF/services/javax.servlet.ServletContainerInitializer service provider configuration file. See the JAR Services API documentation as well as section 8.2.4 of the Servlet 3.0 Final Draft specification for complete details. In combination with web.xml A web application can choose to limit the amount of classpath scanning the Servlet container does at startup either through the metadata-complete attribute in web.xml, which controls scanning for Servlet annotations or through an <absolute-ordering> element also in web.xml, which controls which web fragments (i.e. jars) are allowed to perform a ServletContainerInitializer scan. When using this feature, the SpringServletContainerInitializer can be enabled by adding "spring_web" to the list of named web fragments in web.xml as follows:

<absolute-ordering> <name>some_web_fragment</name> <name>spring_web</name> </absolute-ordering> 
Relationship to Spring's WebApplicationInitializer Spring's WebApplicationInitializer SPI consists of just one method: WebApplicationInitializer#onStartup(ServletContext). The signature is intentionally quite similar to ServletContainerInitializer#onStartup(Set, ServletContext): simply put, SpringServletContainerInitializer is responsible for instantiating and delegating the ServletContext to any user-defined WebApplicationInitializer implementations. It is then the responsibility of each WebApplicationInitializer to do the actual work of initializing the ServletContext. The exact process of delegation is described in detail in the onStartup documentation below. General Notes In general, this class should be viewed as supporting infrastructure for the more important and user-facing WebApplicationInitializer SPI. Taking advantage of this container initializer is also completely optional: while it is true that this initializer will be loaded and invoked under all Servlet 3.0+ runtimes, it remains the user's choice whether to make any WebApplicationInitializer implementations available on the classpath. If no WebApplicationInitializer types are detected, this container initializer will have no effect.

Note that use of this container initializer and of WebApplicationInitializer is not in any way "tied" to Spring MVC other than the fact that the types are shipped in the spring-web module JAR. Rather, they can be considered general-purpose in their ability to facilitate convenient code-based configuration of the ServletContext. In other words, any servlet, listener, or filter may be registered within a WebApplicationInitializer, not just Spring MVC-specific components.

This class is neither designed for extension nor intended to be extended. It should be considered an internal type, with WebApplicationInitializer being the public-facing SPI.

See Also See WebApplicationInitializer Javadoc for examples and detailed usage recommendations.

WebApplicationInitializer

interface WebApplicationInitializer

Interface to be implemented in Servlet 3.0+ environments in order to configure the ServletContext programmatically -- as opposed to (or possibly in conjunction with) the traditional web.xml-based approach.

Implementations of this SPI will be detected automatically by , which itself is bootstrapped automatically by any Servlet 3.0 container. See SpringServletContainerInitializer for details on this bootstrapping mechanism.

Example The traditional, XML-based approach Most Spring users building a web application will need to register Spring's DispatcherServlet. For reference, in WEB-INF/web.xml, this would typically be done as follows:
<servlet> <servlet-name>dispatcher</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/dispatcher-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
The code-based approach with WebApplicationInitializer Here is the equivalent DispatcherServlet registration logic, WebApplicationInitializer-style:
 public class MyWebAppInitializer implements WebApplicationInitializer { @Override public void onStartup(ServletContext container) { XmlWebApplicationContext appContext = new XmlWebApplicationContext(); appContext.setConfigLocation("/WEB-INF/spring/dispatcher-config.xml"); ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(appContext)); dispatcher.setLoadOnStartup(1); dispatcher.addMapping("/"); } }
As an alternative to the above, you can also extend from . As you can see, thanks to Servlet 3.0's new ServletContext#addServlet method we're actually registering an instance of the DispatcherServlet, and this means that the DispatcherServlet can now be treated like any other object -- receiving constructor injection of its application context in this case.

This style is both simpler and more concise. There is no concern for dealing with init-params, etc, just normal JavaBean-style properties and constructor arguments. You are free to create and work with your Spring application contexts as necessary before injecting them into the DispatcherServlet.

Most major Spring Web components have been updated to support this style of registration. You'll find that DispatcherServlet, FrameworkServlet, ContextLoaderListener and DelegatingFilterProxy all now support constructor arguments. Even if a component (e.g. non-Spring, other third party) has not been specifically updated for use within WebApplicationInitializers, they still may be used in any case. The Servlet 3.0 ServletContext API allows for setting init-params, context-params, etc programmatically.

A 100% code-based approach to configuration In the example above, WEB-INF/web.xml was successfully replaced with code in the form of a WebApplicationInitializer, but the actual dispatcher-config.xml Spring configuration remained XML-based. WebApplicationInitializer is a perfect fit for use with Spring's code-based @Configuration classes. See @ Javadoc for complete details, but the following example demonstrates refactoring to use Spring's org.springframework.web.context.support.AnnotationConfigWebApplicationContext in lieu of XmlWebApplicationContext, and user-defined @Configuration classes AppConfig and DispatcherConfig instead of Spring XML files. This example also goes a bit beyond those above to demonstrate typical configuration of the 'root' application context and registration of the ContextLoaderListener:
 public class MyWebAppInitializer implements WebApplicationInitializer { @Override public void onStartup(ServletContext container) { // Create the 'root' Spring application context AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); rootContext.register(AppConfig.class); // Manage the lifecycle of the root application context container.addListener(new ContextLoaderListener(rootContext)); // Create the dispatcher servlet's Spring application context AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext(); dispatcherContext.register(DispatcherConfig.class); // Register and map the dispatcher servlet ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext)); dispatcher.setLoadOnStartup(1); dispatcher.addMapping("/"); } }
As an alternative to the above, you can also extend from . Remember that WebApplicationInitializer implementations are detected automatically -- so you are free to package them within your application as you see fit. Ordering WebApplicationInitializer execution WebApplicationInitializer implementations may optionally be annotated at the class level with Spring's @org.springframework.core.annotation.Order annotation or may implement Spring's org.springframework.core.Ordered interface. If so, the initializers will be ordered prior to invocation. This provides a mechanism for users to ensure the order in which servlet container initialization occurs. Use of this feature is expected to be rare, as typical applications will likely centralize all container initialization within a single WebApplicationInitializer. Caveats web.xml versioning

WEB-INF/web.xml and WebApplicationInitializer use are not mutually exclusive; for example, web.xml can register one servlet, and a WebApplicationInitializer can register another. An initializer can even modify registrations performed in web.xml through methods such as ServletContext#getServletRegistration(String). However, if WEB-INF/web.xml is present in the application, its version attribute must be set to "3.0" or greater, otherwise ServletContainerInitializer bootstrapping will be ignored by the servlet container.

Mapping to '/' under Tomcat

Apache Tomcat maps its internal DefaultServlet to "/", and on Tomcat versions <= 7.0.14, this servlet mapping cannot be overridden programmatically. 7.0.15 fixes this issue. Overriding the "/" servlet mapping has also been tested successfully under GlassFish 3.1.

Exceptions

HttpMediaTypeNotAcceptableException

open class HttpMediaTypeNotAcceptableException : HttpMediaTypeException

Exception thrown when the request handler cannot generate a response that is acceptable by the client.

HttpMediaTypeNotSupportedException

open class HttpMediaTypeNotSupportedException : HttpMediaTypeException

Exception thrown when a client POSTs, PUTs, or PATCHes content of a type not supported by request handler.

HttpRequestMethodNotSupportedException

open class HttpRequestMethodNotSupportedException : ServletException

Exception thrown when a request handler does not support a specific request method.

HttpSessionRequiredException

open class HttpSessionRequiredException : ServletException

Exception thrown when an HTTP request handler requires a pre-existing session.