Spring MVC, like many other web frameworks, is designed using a "single sign-on (front controller)" design pattern, where a central Servlet
, DispatcherServlet
, provides common algorithm for processing requests, and the actual work is done by custom delegate components. This model is flexible and supports a variety of workflows.
DispatcherServlet
, like any other Servlet
, must be declared and rendered according to the Servlet specification using Java configuration or in web.xml
. In turn, DispatcherServlet
uses the Spring configuration to discover the delegate beans it needs to render requests, recognize views, handle exceptions, etc.
The following Java configuration example registers and initializes a DispatcherServlet
that is automatically discovered by the servlet container:
public class MyWebApplicationInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) {
// Load the Spring web application configuration
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(AppConfig.class);
// Create and register DispatcherServlet
DispatcherServlet servlet = new DispatcherServlet(context);
ServletRegistration.Dynamic registration = servletContext.addServlet("app", servlet);
registration.setLoadOnStartup(1);
registration.addMapping("/app/*");
}
}
class MyWebApplicationInitializer : WebApplicationInitializer {
override fun onStartup(servletContext: ServletContext) {
// Load the Spring web application configuration
val context = AnnotationConfigWebApplicationContext()
context.register(AppConfig::class.java)
// Create and register DispatcherServlet
val servlet = DispatcherServlet(context)
val registration = servletContext.addServlet("app", servlet)
registration.setLoadOnStartup(1)
registration.addMapping("/app/*")
}
}
AbstractAnnotationConfigDispatcherServletInitializer
and override the specified methods.
AnnotationConfigWebApplicationContext
can be used as an alternative to
GenericWebApplicationContext
.
The following configuration example web.xml
registers and initializes the DispatcherServlet
:
<web-app>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/app-context.xml</param-value>
</context-param>
<servlet>
<servlet-name>app</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>app</servlet-name>
<url-pattern>/app/*</url-pattern>
</servlet-mapping>
</web-app>
Filter
and
Servlet
declarations are found in the Spring configuration and registered in the servlet container.
GO TO FULL VERSION