Features of Spring MVC
The Spring MVC framework is DispatcherServlet
designed around, which Servlet
distributes requests to various processors and supports configurable processor mapping, view rendering, localization, time zone and theme rendering, and file uploading.
Handlers are classes and methods annotated with @Controller
and in an application, @RequestMapping
and Spring provides a very diverse and flexible configuration for handler methods.
After Spring 3.0, @Controller
annotation mechanisms, @PathVariable
annotations, and some other features are provided, which you can use to develop RESTful web sites and applications.
Spring MVC has the following features:
- Clear separation of duties. Each role - controller, validator, command object, form object, model object,
DispatcherServlet
, handler mapping, view resolver, and many more - can be done by the corresponding object. - Powerful, intuitive framework and configuration of application beans. This configuration capability includes the ability to make simple references from different contexts, such as business objects, validators, etc. in web controllers.
- Powerful adaptability, non-invasiveness and flexibility. Spring MVC allows you to define arbitrary controller method signatures, and in specific scenarios you can also add appropriate annotations (such as
@RequestParam
,@RequestHeader
, ,@PathVariable
etc.) - Reusable business code keeps you away from duplicate code. You can use existing business objects as command objects or form objects without having them inherit from a framework-provided base class.
- Customizable data binding and validation. Type mismatches are only considered application-level validation errors, and incorrect values, localized dates, numeric bindings, etc. are saved. You no longer need to use full String fields in form objects and then manually convert them to business objects.
- Customizable handler mapping and view resolution. Handler mappings and view resolution strategies range from simple URL-based configuration to fine-grained specialized resolution strategies, all supported by Spring. In this regard, Spring is more flexible than some web frameworks that rely on specific technologies.
- Flexible model delivery. Spring uses a Map of name/value pairs for the model, which makes the model easy to integrate and pass to any type of view technology.
- Customizable localization information, time zone and theme parsing. Supports JSP technology with/without Spring tag library, supports JSTL, supports Velocity templates without additional configuration, etc. ;
- A simple but powerful JSP tag library, commonly called Spring tag library, which provides support for some features such as data binding, theme support, etc. These custom tags provide maximum flexibility for marking up your code.
- A JSP form tag library introduced in Spring 2.0. It makes writing forms in JSP pages much easier.
- Added a bean type whose lifetime is only bound to the current HTTP request or HTTP session.
Workflow of DispatcherServlet
The Spring MVC framework is request-driven: all designs revolve around a central Servlet
point, which is responsible for dispatching all requests to controllers; and provides other functionality required for web application development. DispatcherServlet
Seamless integration with the Spring IoC container means that you can use any feature provided by Spring in Spring MVC.
The following figure shows the DispatcherServlet
workflow of processing requests in Spring Web MVC, DispatcherServlet
which is actually a "front controller" design pattern:
Based on Spring Boot , Spring MVC can be used directly, unless there are very personalized requirements, the related configuration does not need to be manually configured.
Configuration of DispatcherServlet
DispatcherServlet
In fact, it is one Servlet
(it inherits from the HttpServlet
base class), and it also needs to web.xml
be declared in the configuration file of your web application. You need to map the request web.xml
you want to DispatcherServlet
handle to the corresponding URL in the file. This is the standard Java EE servlet configuration; the following code shows the DispatcherServlet
declaration of the pair and path mapping:
<web-app>
<servlet>
<servlet-name>example</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>example</servlet-name>
<url-pattern>/example/*</url-pattern>
</servlet-mapping>
</web-app>
In the above example, all /example
requests with a path starting with will be processed with example
the name DispatcherServlet
.
In a Servlet 3.0+ environment, you can also configure the servlet container programmatically. The following is an example of such a code-based configuration, which web.xml
is equivalent to the configuration file defined above.
public class MyWebApplicationInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) {
ServletRegistration.Dynamic registration = container.addServlet("dispatcher", new DispatcherServlet());
registration.setLoadOnStartup(1);
registration.addMapping("/example/*");
}
}
WebApplicationInitializer
is an interface provided by Spring MVC that will look up all your code-based configurations and apply them to initialize the web container for Servlet 3 and above. It has an abstract implementation AbstractDispatcherServletInitializer
to simplify DispatcherServlet
registration: you just need to specify its servlet mapping.
WebApplicationContext
In Spring MVC, each DispatcherServlet
holds its own context object WebApplicationContext
, which in turn inherits all beans already defined in the root WebApplicationContext
object. These inherited beans can be overloaded in specific servlet instances, and in each servlet instance you can also define new beans under its scope.
DispatcherServlet
During the initialization process, Spring MVC will WEB-INF
look for a configuration file named [servlet-name]-servlet.xml in the directory of your web application and create the beans defined in it. If beans with the same name exist in the global context, they will be overwritten by newly defined beans with the same name.
The following DispatcherServlet
servlet configuration (defined in the web.xml file):
<web-app>
<servlet>
<servlet-name>golfing</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>golfing</servlet-name>
<url-pattern>/golfing/*</url-pattern>
</servlet-mapping>
</web-app>
With the above servlet configuration file, you also need to create a file /WEB-INF/
under the path in the application, in which all Spring MVC related components (such as beans, etc.) are defined.golfing-servlet.xml
To customize DispatcherServlet
the configuration, add some servlet initialization parameters (through init-param
elements) to the servlet declaration element. The list of optional parameters for this element is as follows:
contextClass |
Any WebApplicationContext class that implements an interface. This class initializes the context object that the servlet needs to use. By default, the framework uses an XmlWebApplicationContext object. |
contextConfigLocation |
A string specifying the path to the context configuration file that will be passed to contextClass the specified context instance object. This string can contain multiple strings, separated by commas, so that you can configure multiple contexts. For beans defined repeatedly in multiple contexts, the last bean definition loaded takes precedence |
namespace |
WebApplicationContext namespace. Default is[servlet-name]-servlet |
Implementation of Spring MVC: Built-in Components in WebApplicationContext
WebApplicationContext
Inherited from ApplicationContext
, it provides some features that are often used in web applications. WebApplicationContext
is bound in ServletContext
. If you need to get it, you can RequestContextUtils
get the context of this web application through the static method in the utility class WebApplicationContext
.
Spring uses specific beans DispatcherServlet
built in to handle requests, render views, etc., which are part of the Spring MVC framework. WebApplicationContext
If you want to specify which specific beans to use, you can WebApplicationContext
simply configure them in . Of course this is only optional, Spring MVC maintains a default list of beans, if no special configuration is made, the framework will use the default beans. DispatcherServlet
These beans are depended on as shown in the following table.
HandlerMapping |
Processor mapping. It maps incoming container requests to specific processors and a series of pre-processors and post-processors (ie, processor interceptors) according to certain rules. The exact rules vary depending HandlerMapping on the implementation of the class. One of its most common implementations allows you to add annotations to controllers to configure request paths. Of course, other implementations also exist. |
HandlerAdapter |
processor adapter. After getting the handler corresponding to the request, the adapter will be responsible for calling the handler, which makes it DispatcherServlet unnecessary to care about the specific calling details. For example, if you want to call a controller based on annotation configuration, you need to parse some corresponding information from many annotations before calling. Therefore, HandlerAdapter the main task is to DispatcherServlet shield these specific details. |
HandlerExceptionResolver |
Handler exception parser. It is responsible for mapping caught exceptions to different views, and also supports more complex exception handling code. |
ViewResolver |
View resolver. It is responsible for mapping a string (String) representing the logical view name to the actual view type View . |
LocaleResolver & LocaleContextResolver |
Locale resolver and locale context resolver. They are responsible for parsing the client's region information and even time zone information, providing support for internationalized view customization. |
ThemeResolver |
Topic parser. It is responsible for parsing the themes available in your web application, for example, providing some customized layouts, etc. |
MultipartResolver |
Parse multi-part transmission requests, such as supporting file uploads through HTML forms, etc. |
FlashMapManager |
FlashMap manager. It can store and retrieve FlashMap objects between requests. The latter can be used to pass data between requests, usually in the context of request redirection. |
This list of beans is kept in a file org.springframework.web.servlet
under the package. DispatcherServlet.properties
These beans have some basic default behavior. Some of the default configurations they provide may need to be customized in the future. For example, it is often necessary to configure InternalResourceViewResolver
the properties provided by the class prefix
to point to the directory where the view files are located.
WebApplicationContext
Once you configure a particular bean in the web application context (for example InternalResourceViewResolver
), it overrides the default implementation of that bean. For example, if you configure the default implementation that InternalResourceViewResolver
the framework will no longer use .ViewResolver
Configuring Spring MVC can be configured through Java programming configuration or through the MVC XML namespace. Without going into details, you can refer to Spring MVC Configuration .
DispatcherServlet processing flow
After the configuration is complete DispatcherServlet
, requests will begin to pass through this DispatcherServlet
. At this point, DispatcherServlet
requests are processed in the following order:
- First, search for the application's context object
WebApplicationContext
and bind it as an attribute to the request so that controllers and other components can use it. The key name of the property defaults toDispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE
- Bind a locale resolver to a request so that other components can get locale-related information when processing the request (rendering views, preparing data, etc.). If your app doesn't need to parse locale-related information, just ignore it
- Bind a theme resolver to the request so that other components (like views, etc.) can know which theme file to render. Again, if you don't need to use theme-related features, just ignore it
- If you configure a multipart file handler, then the framework will look to see if the file is multipart (multipart sequential uploads). If so, wrap the request into an
MultipartHttpServletRequest
object for further processing by other components in the processing chain. - Find a suitable handler for the request. If a corresponding processor can be found, the entire execution chain associated with that processor (pre-processor, post-processor, controller, etc.) is executed to complete the preparation of the corresponding model or rendering of the view
- If the handler returns a model, the framework will render the corresponding view. If no model is returned (probably because the previous and subsequent processors intercepted the request for some reason, such as security issues), the framework will not render any views, and it is believed that the processing of the request may have been completed by the processing chain span
If exceptions are thrown during the processing of the request, WebApplicationContext
the exception handler defined in the context object will be responsible for catching those exceptions. By configuring your own exception handler, you can customize the way you handle exceptions.
Spring DispatcherServlet
also allows the handler to return a last-modification-date value as defined in the Servlet API specification. The way to determine the last modification time of a request is straightforward: DispatcherServlet
it looks for the appropriate handler map to find the handler for the request, and then checks to see if it implements the LastModified interface. If so, call the long getLastModified(request)
method of the interface and return the return value to the client.
https://www.tianmaying.com/tutorial/spring-mvc-DispatcherServlet