Detailed SpringMVC operating mechanism - to learn basic skills, good easy walk

Detailed SpringMVC operating mechanism - to learn basic skills, good easy walk

Description: Learn SpringMVC operating mechanism is conducive to a better understanding of SpringMVC framework in the development process to be able to quickly locate the problem. Meanwhile SSM project to build more understanding of basic configuration. In short, a lot of advantages;

The basic concept SpringMVC

SpringMVC framework: belonging SpringFrameWork successor, has been integrated in the Spring Web Flow inside (from Baidu Encyclopedia). In summary, SpringMVC frame part belonging Spring architecture. In the actual development, which is responsible for receiving the HTTP request, data processing, and the like in response to the request web layer functions implemented; it is also referred to as a Web layer SpringMVC framework; its design architecture is based on the MVC architecture.

MVC architecture concepts

M (the Model) model, V (View) view, C (Controller) The controller three separate software design; primary object model layer and let V M view layers were separated, only focus to realize their functions. C controller layer through the interaction between them coordinated cross. MVC hierarchical design reduces the coupling between code that is conducive to code maintenance. FIG MVC architecture is as follows:

Coupling : it refers to the interdependence between the service code, the function code different hierarchical unclear. Mixed together with, similar to the coils, as shown below: left coupling is high, there is a low degree of coupling of FIG;

The basic structure of SpringMVC

SpringMVC like a car, a lot of framework members combined together form SpringMVC. SpringMVC member mainly composed of the DispatcherServlet (distributor), HandlerMapping (process mapper), HandlerAdapter (processing adapter), ViewResolver (view resolver) other major components.

  1. DispatcherServlet (dispatcher): it belongs to SpringMVC core importance like the engine of a car. It is mainly used to receiving the request, the corresponding results, the scheduling process other components / response request. Because of its presence, to reduce the coupling between the various components;
  2. The HandlerMapping (Mapper process): The URL to match to the requesting program "Configuration / notes" Handler arranged manner, and then the processor returns Handler chain.
  3. HandlerAdapter is (adapter Processing): The rule processor to perform the corresponding Handler, returns the result of the processor;
  4. ViewResolver (resolver view): the adapter returns the results ModelAndView, parsed into a corresponding view object View, View finally render the processing result to the user through display pages.

Summary: These are the main components around the DispatcherServlet (distributor) scheduling. We can not directly interact with each other. SpringMVC flowchart as follows:
Here Insert Picture Description

SpringMVC source code analysis (read above is enough to remember, such as knowledge base to learn more)

  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

Recommend View code with the Idea, not the convenience of not. Use ctrl + click DispatcherServlet into the source file; DispatcherServlet first look at the source code inheritance / implementation diagram. As shown below:
Here Insert Picture Description

Description : The following operational mechanism based on source code analysis DispatcherServlet process, it will not explain the specific role of each method;

The first question: DispatcherServlet how to get the user's HTTP request?

From the chart shows, DispatcherServlet inherited HttpServlet, used struts are aware of the role HtppServlet. It is treated with a HTTP request. Specific self-Baidu. HttpServlet.class source method are summarized as follows:
Here Insert Picture Description

Note where the red mark. DispatcherServlet class inherits the abstract class FrameworkServlet. And overrides the service method in the abstract class HttpServlet in FrameworkServlet. Source coating method as follows:

/**
*FrameworkServlet.class源码(行数:432——440)
**/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpMethod httpMethod = HttpMethod.resolve(request.getMethod());
        if (httpMethod != HttpMethod.PATCH && httpMethod != null) {
            super.service(request, response);
        } else {
            this.processRequest(request, response);
        }

    }

This shows that when the HTTP request is over, will perform the above method, if the normal HTTP request, the HttpServlet class service method calls. Determining whether the request type, and the callback doGet / doPost method FrameworkServlet abstract class. ProcessRequest final execution method. processRequest source as shown below:
Here Insert Picture Description

Note that reference numeral place; the doService is an abstract method of the abstract class FrameworkServlet. And implemented in a subclass of DispatcherServlet.

Summary: This is the date, the known DispatcherServlet FrameworkServlet abstract class by inheritance, FrameworkServlet abstract class HttpServlet class overrides the method of service give the HTTP request;

Second question: HandlerMapping, HandlerAdapte and ViewResolver is how to initialize?
Look HttpServletBean.class source class init method. As follows:

/**
* HttpServletBean.class中66-85行
**/
public final void init() throws ServletException {
        PropertyValues pvs = new HttpServletBean.ServletConfigPropertyValues(this.getServletConfig(), this.requiredProperties);
        if (!pvs.isEmpty()) {
            try {
                BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
                ResourceLoader resourceLoader = new ServletContextResourceLoader(this.getServletContext());
                bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, this.getEnvironment()));
                this.initBeanWrapper(bw);
                bw.setPropertyValues(pvs, true);
            } catch (BeansException var4) {
                if (this.logger.isErrorEnabled()) {
                    this.logger.error("Failed to set bean properties on servlet '" + this.getServletName() + "'", var4);
                }

                throw var4;
            }
        }

        this.initServletBean();
    }

HttpServletBean in class init () overrides the init method of the servlet class. init process execution time servlet configuration with load-on-startup label relevant, as shown below:
Here Insert Picture Description
If the value equals 0, then performing the Servlet instantiation, the specific time interval determined by the value, the greater the value , then the later execution. If less than 0 or is not configured, the first time before the synchronization request is performed (the method is performed only once);
wherein the method involves the init BeanWrapper, PropertyValues, ResourceLoader, initServletBean method

  1. PropertyValues: Get the init-param servlet Web.xml inside;
  2. BeanWrapper: bean encapsulates the behavior provided to set and get property values, it has a corresponding BeanWrapperImpl;
  3. ResourceLoader: the interface is just a method getResource (String location), you can load the file resource according to a resource address. classpath: SpringMVC source specified in this manner bean frame profile;
  4. initServletBean (): in HttpServletBean classes provide a reference, it is embodied in FrameworkServlet subclass. Source as follows:
    Here Insert Picture Description

initServletBean method calls initWebApplicationContext method. SpringMVC used to initialize the context. While simultaneously execute onRefresh () method synchronized key. Source follows:
Here Insert Picture Description
OnRefresh methods only provide reference FrameworkServlet, it is embodied in DispatcherServlet subclass. Source as follows:
Here Insert Picture Description
OnRefresh method called initStrategies method. In initStrategies initialized SpringMVC components.

//初始化上传文件解析器
initMultipartResolver(context);

//初始化本地解析器
initLocaleResolver(context);

//初始化主题解析器
initThemeResolver(context);

//初始化映射处理器
initHandlerMappings(context);

//初始化适配器处理器
initHandlerAdapters(context);

//初始化异常处理器
initHandlerExceptionResolvers(context);

//初始化请求到视图名翻译器
initRequestToViewNameTranslator(context);

//初始化视图解析器
initViewResolvers(context);

Summary: Currently the only source code analysis involves three categories, namely: FrameworkServlet, DispatcherServlet, HttpServletBean. They each do what?

  1. HttpServletBean is mainly to get the value of the label web.xml configuration file;
  2. FrameworkServlet main achievement initialize SpringMVC context;
  3. DispatcherServlet mainly achieved SpringMVC initialization of various components;

Guess you like

Origin blog.csdn.net/u012475786/article/details/89480938
Recommended