Let's first look at what MVC mode is
MVC is a design pattern
The schematic diagram of MVC is as follows:
A brief introduction to SpringMVC
The SpringMVC framework is request driven, designed around servlets, sends requests to controllers, and then displays the view of request results through model objects and dispatchers. The core class is DispatcherServlet, which is a Servlet. The top level is the Servlet interface implemented.
SpringMVC uses
It needs to be on the web DispatcherServlet is configured in XML. And the Spring listener ContextLoaderListener needs to be configured
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet </servlet-class> <!-- If not set init-param Label, you must/WEB-INF/Create under xxx-servlet.xml File, where xxx yes servlet-name The name of the configuration in. --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/springmvc-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
How SpringMVC works (important)
Simply put:
The client sends the request - > the front-end controller DispatcherServlet accepts the client request - > find the Handler corresponding to the Handler mapping parsing request - > the handleradapter will call the real processor to start processing the request according to the Handler, And process the corresponding business logic - > the processor returns a model view modelandview - > the view parser parses - > returns a view object - > the front-end controller DispatcherServlet render data (Moder) - > returns the obtained view object to the user
As shown in the following figure:
A clerical error in the above figure: the Spring MVC entry function, that is, the front-end controller DispatcherServlet, is used to receive requests and respond to results.
Process description (important):
(1) The client (browser) sends a request directly to the DispatcherServlet.
(2) DispatcherServlet calls HandlerMapping according to the request information and parses the Handler corresponding to the request.
(3) After resolving to the corresponding Handler (that is, the Controller controller we usually call), the Handler adapter starts processing.
(4) The HandlerAdapter will call the real processor to start processing the request according to the Handler and process the corresponding business logic.
(5) After processing the business, the processor will return a ModelAndView object. Model is the returned data object and View is a logical View.
(6) ViewResolver will find the actual View based on the logical View.
(7) Dispatterservlet transfers the returned Model to View (View rendering).
(8) Return View to requestor (browser)
Description of important SpringMVC components
1. Front end controller DispatcherServlet (no engineer development required), provided by the framework (important)
Function: the entry function of Spring MVC. Receive the request and respond to the result, which is equivalent to the transponder and the central processing unit. With DispatcherServlet, the coupling between other components is reduced. When a user request arrives at the front-end controller, it is equivalent to c in mvc mode. DispatcherServlet is the center of the whole process control. It calls other components to process the user request. The existence of DispatcherServlet reduces the coupling between components.
2. Processor mapper handlermapping (without Engineer Development), provided by the framework
Function: find the Handler according to the requested url. HandlerMapping is responsible for finding the Handler (Controller) according to the user request. SpringMVC provides different mappers to implement different mapping methods, such as configuration file method, implementation interface method, annotation method, etc.
3. Processor adapter HandlerAdapter
Function: execute Handler according to specific rules (rules required by HandlerAdapter)
Execute the processor through the HandlerAdapter, which is an application of the adapter mode. More types of processors can be executed through the extension adapter.
4. Processor Handler (engineer development required)
Note: when writing a Handler, follow the requirements of the HandlerAdapter so that the adapter can correctly execute the Handler
The Handler is the back-end controller following the DispatcherServlet front-end controller. Under the control of the DispatcherServlet, the Handler processes specific user requests.
Since Handler involves specific user business requests, engineers are generally required to develop handlers according to business requirements.
5. View resolver (without Engineer Development), provided by the framework
Function: perform view resolution, and resolve to a real view according to the logical view name
The View Resolver is responsible for generating the View view from the processing results. The View Resolver first resolves the logical View name into the physical View name, that is, the specific page address, then generates the View object, and finally renders the View to display the processing results to the user through the page. springmvc framework provides many View types, including jstlView, freemarkerView, pdfView, etc.
Generally, model data needs to be displayed to users through pages through page labels or page template technology. Engineers need to develop specific pages according to business needs.
6. View view (engineer development required)
View is an interface. The implementation class supports different view types (jsp, freemaker, pdf...)
Note: the processor Handler (that is, the Controller we usually call) and the view layer view need to be manually developed by ourselves. Other components, such as the front-end Controller DispatcherServlet, the processor mapper HandlerMapping, and the processor adapter HandlerAdapter, are provided to us by the framework and do not need to be developed manually.
Detailed analysis of DispatcherServlet
First, look at the source code:
package org.springframework.web.servlet; @SuppressWarnings("serial") public class DispatcherServlet extends FrameworkServlet { public static final String MULTIPART_RESOLVER_BEAN_NAME = "multipartResolver"; public static final String LOCALE_RESOLVER_BEAN_NAME = "localeResolver"; public static final String THEME_RESOLVER_BEAN_NAME = "themeResolver"; public static final String HANDLER_MAPPING_BEAN_NAME = "handlerMapping"; public static final String HANDLER_ADAPTER_BEAN_NAME = "handlerAdapter"; public static final String HANDLER_EXCEPTION_RESOLVER_BEAN_NAME = "handlerExceptionResolver"; public static final String REQUEST_TO_VIEW_NAME_TRANSLATOR_BEAN_NAME = "viewNameTranslator"; public static final String VIEW_RESOLVER_BEAN_NAME = "viewResolver"; public static final String FLASH_MAP_MANAGER_BEAN_NAME = "flashMapManager"; public static final String WEB_APPLICATION_CONTEXT_ATTRIBUTE = DispatcherServlet.class.getName() + ".CONTEXT"; public static final String LOCALE_RESOLVER_ATTRIBUTE = DispatcherServlet.class.getName() + ".LOCALE_RESOLVER"; public static final String THEME_RESOLVER_ATTRIBUTE = DispatcherServlet.class.getName() + ".THEME_RESOLVER"; public static final String THEME_SOURCE_ATTRIBUTE = DispatcherServlet.class.getName() + ".THEME_SOURCE"; public static final String INPUT_FLASH_MAP_ATTRIBUTE = DispatcherServlet.class.getName() + ".INPUT_FLASH_MAP"; public static final String OUTPUT_FLASH_MAP_ATTRIBUTE = DispatcherServlet.class.getName() + ".OUTPUT_FLASH_MAP"; public static final String FLASH_MAP_MANAGER_ATTRIBUTE = DispatcherServlet.class.getName() + ".FLASH_MAP_MANAGER"; public static final String EXCEPTION_ATTRIBUTE = DispatcherServlet.class.getName() + ".EXCEPTION"; public static final String PAGE_NOT_FOUND_LOG_CATEGORY = "org.springframework.web.servlet.PageNotFound"; private static final String DEFAULT_STRATEGIES_PATH = "DispatcherServlet.properties"; protected static final Log pageNotFoundLogger = LogFactory.getLog(PAGE_NOT_FOUND_LOG_CATEGORY); private static final Properties defaultStrategies; static { try { ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, DispatcherServlet.class); defaultStrategies = PropertiesLoaderUtils.loadProperties(resource); } catch (IOException ex) { throw new IllegalStateException("Could not load 'DispatcherServlet.properties': " + ex.getMessage()); } } /** Detect all HandlerMappings or just expect "handlerMapping" bean? */ private boolean detectAllHandlerMappings = true; /** Detect all HandlerAdapters or just expect "handlerAdapter" bean? */ private boolean detectAllHandlerAdapters = true; /** Detect all HandlerExceptionResolvers or just expect "handlerExceptionResolver" bean? */ private boolean detectAllHandlerExceptionResolvers = true; /** Detect all ViewResolvers or just expect "viewResolver" bean? */ private boolean detectAllViewResolvers = true; /** Throw a NoHandlerFoundException if no Handler was found to process this request? **/ private boolean throwExceptionIfNoHandlerFound = false; /** Perform cleanup of request attributes after include request? */ private boolean cleanupAfterInclude = true; /** MultipartResolver used by this servlet */ private MultipartResolver multipartResolver; /** LocaleResolver used by this servlet */ private LocaleResolver localeResolver; /** ThemeResolver used by this servlet */ private ThemeResolver themeResolver; /** List of HandlerMappings used by this servlet */ private List<HandlerMapping> handlerMappings; /** List of HandlerAdapters used by this servlet */ private List<HandlerAdapter> handlerAdapters; /** List of HandlerExceptionResolvers used by this servlet */ private List<HandlerExceptionResolver> handlerExceptionResolvers; /** RequestToViewNameTranslator used by this servlet */ private RequestToViewNameTranslator viewNameTranslator; private FlashMapManager flashMapManager; /** List of ViewResolvers used by this servlet */ private List<ViewResolver> viewResolvers; public DispatcherServlet() { super(); } public DispatcherServlet(WebApplicationContext webApplicationContext) { super(webApplicationContext); } @Override protected void onRefresh(ApplicationContext context) { initStrategies(context); } protected void initStrategies(ApplicationContext context) { initMultipartResolver(context); initLocaleResolver(context); initThemeResolver(context); initHandlerMappings(context); initHandlerAdapters(context); initHandlerExceptionResolvers(context); initRequestToViewNameTranslator(context); initViewResolvers(context); initFlashMapManager(context); } }
Attribute beans in the DispatcherServlet class:
- HandlerMapping: used for handlers mapping requests and a series of pre-processing and post-processing for interceptors. Most of them are annotated with @Controller.
- HandlerAdapter: an adapter that helps DispatcherServlet handle mapping request handlers, regardless of which handler is actually invoked. --
- ViewResolver: resolves the actual View type according to the actual configuration.
- ThemeResolver: addresses topics that Web applications can use, such as providing personalized layouts.
- MultipartResolver: parses multipart requests to support uploading files from HTML forms-
- FlashMapManager: stores and retrieves flashmaps that can be used to pass a request attribute to the input and output of another request, usually for redirection.
In the Web MVC framework, each DispatcherServlet has its own WebApplicationContext, which inherits the ApplicationContext. WebApplicationContext contains all the basic framework beans shared between its context and Servlet instances.
HandlerMapping
The HandlerMapping interface processes the requested mapping. The implementation class of the HandlerMapping interface:
- The SimpleUrlHandlerMapping class maps URL s to the Controller class through a configuration file.
- The DefaultAnnotationHandlerMapping class maps URL s to the Controller class through annotations.
HandlerAdapter
HandlerAdapter interface - process request mapping
AnnotationMethodHandlerAdapter: map the request URL to the method of the Controller class through annotation.
HandlerExceptionResolver
HandlerExceptionResolver interface - exception handling interface
- SimpleMappingExceptionResolver handles exceptions through the configuration file.
- AnnotationMethodHandlerExceptionResolver: exception handling through annotations.
ViewResolver
The ViewResolver interface parses the View view.
The UrlBasedViewResolver class passes a View name to a View for processing through the configuration file.