The MVC Model Explains a little Classroom (Multi-shore College)

Posted by millercj on Tue, 10 Sep 2019 06:47:11 +0200

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 Spring MVC

Spring MVC framework is driven by requests. It is designed around Servlet and sends requests to the controller. Then it shows the view of request results through model objects and dispatchers. The core class is Dispatcher Servlet, which is a Servlet. The top layer is the Servlet interface.

Spring MVC uses

Dispatcher Servlet needs to be configured in web.xml. And you need to configure the Spring listener ContextLoaderListener

<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 The label must be/WEB-INF/Create the following xxx-servlet.xml Documents, where xxx yes servlet-name Name of 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>

Working Principle of Spring MVC (Important)

In short:

Client Sending Request - > Front-end Controller Dispatcher Servlet Accepts Client Request - > Find Handler Mapping Resolution Request corresponding to Handler - > Handler Adapter will call the real processor to process the request according to Handler, and process the corresponding business logic - > Processor returns a model view M. Model AndView - > View Parser parses - > Returns a View Object - > Front-end Controller Dispatcher Servlet Rendering Data (Moder) - > Returns the View Object to the User

As shown in the following figure:

One minor problem with the slip of the pen: Spring MVC's entry function, the front-end controller Dispatcher Servlet, serves to receive requests and respond to results.

Process description (important):

(1) The client (browser) sends the request directly to the Dispatcher Servlet.

(2) Dispatcher Servlet calls Handler Mapping based on request information and parses the corresponding Handler of the request.

(3) After resolving to the corresponding Handler (that is, the Controller controller as we usually call it), it is processed by the Handler Adapter adapter.

(4) Handler Adapter will call the real processor to process the request and process the corresponding business logic according to Handler.

(5) After processing the business, the processor returns a Model AndView object, which is the data object returned, and View is a logical View.

(6) ViewResolver looks up the actual View based on the logical View.

(7) DispaterServlet passes the returned Model to View (view rendering).

(8) Return View to the requester (browser)

Description of Important Components of Spring MVC

1. Front-end controller Dispatcher Servlet (no need for engineer development), provided by the framework (important)

Function: Spring MVC entry function. Receiving requests and responding to results are equivalent to transponders and CPUs. Dispatcher Servlet reduces the coupling between other components. The user request arrives at the front-end controller, which is equivalent to c in mvc mode. Dispatcher Servlet is the center of the whole process control. It calls other components to process the user's request. The existence of Dispatcher Servlet reduces the coupling between components.

2. Processor mapper Handler Mapping (no need for engineer development), provided by the framework

Function: Find Handler based on the requested url. Handler Mapping is responsible for finding Handler, or Controller, according to user's request. Spring MVC provides different mappers to implement different mapping methods, such as configuration file, interface, annotation, etc.

3. Processor adapter Handler Adapter

Function: Execute Handler according to specific rules (rules required by Handler Adapter)
Processors are executed through the Handler Adapter, which is an application of the adapter pattern. More types of processors can be executed by extending the adapter.

4. Processor Handler (Required Engineer Development)

Note: Write Handler according to the requirements of Handler Adapter, so that the adapter can correctly execute Handler.
Handler is the back-end controller following the front-end controller of Dispatcher Servlet. Under the control of Dispatcher Servlet, Handler processes specific user requests.
As Handler involves specific user business requests, engineers are generally required to develop Handler according to business requirements.

5. View resolver (no need for engineer development), provided by framework

Function: View parsing, parsing into a real view based on the logical view name
View Resolver is responsible for generating View view from processing results. View Resolver first parses the logical view name into physical view name, that is, specific page address, and regenerates the View view object. Finally, View is rendered to display the processing results to users through the page. The spring MVC framework provides many types of view views, including jstlView, freemarkerView, pdfView, etc.
Generally, the model data need to be displayed to users through page label or page template technology. Engineers need to develop specific pages according to business needs.

6. View View (Required Engineer Development)

View is an interface that implements classes that support different View types (jsp, freemarker, pdf...)

Note: Processor Handler (that is, Controller Controller Controller) and view layer view need to be manually developed by ourselves. Other components such as the front-end controller Dispatcher Servlet, processor mapper Handler Mapping, processor adapter Handler Adapter and so on are provided by the framework, which does not need to be manually developed.

Detailed parsing of Dispatcher Servlet

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 Dispatcher Servlet class:

  • Handler Mapping: For handlers mapping requests and a series of pre-and post-processing for interceptors, most are annotated with @Controller.
  • Handler Adapter: An adapter that helps the Dispatcher Servlet process the mapping request handler, regardless of which handler is actually invoked. ---
  • ViewResolver: Resolve the actual View type based on the actual configuration.
  • Theme Resolver: Solves topics that Web applications can use, such as providing personalized layouts.
  • MultipartResolver: Parses multiple requests to support uploading files from HTML forms. -
  • FlashMap Manager: Stores and retrieves FlashMaps that can be used to pass one request attribute to the input and output of another request, usually for redirection.

In the Web MVC framework, each Dispatcher Servlet has its own Web Application Context, which inherits it. Web Application Context contains all the basic framework beans shared between its context and Servlet instances.

HandlerMapping

Handler Mapping Interface Processing Request Mapping Interface Implementing Class:

  • The SimpleUrlHandlerMapping class maps URL s to Controller classes through configuration files.
  • The DefaultAnnotationHandlerMapping class maps URL s to Controller classes through annotations.

HandlerAdapter

Handler Adapter Interface - Processing Request Mapping

Annotation Method Handler Adapter: Mapping request URL s to methods of the Controller class through annotations.

HandlerExceptionResolver

Handler Exception Resolver Interface - Exception Handling Interface

  • SimpleMapping Exception Resolver handles exceptions through configuration files.
  • Annotation Method Handler Exception Resolver: Exception handling through annotations.

ViewResolver

The ViewResolver interface parses the View view.

The UrlBasedViewResolver class handles a view name to a View through a configuration file.

Topics: Spring xml Attribute JSP