SpringMVC execution process and operating principle

What is MVC?

MVC is the abbreviation of Model, View, and Controller, which respectively represent the three responsibilities in Web applications. MVC is a software design specification. It organizes code by separating business logic, data, and display, reducing the two-way coupling between view and business logic.

  • Model (model) : The data model provides the data to be displayed, so it contains data and behavior. It can be considered as a domain model or JavaBean component (including data and behavior), but it is generally separated now: Value Object (data Dao) and Service layer (behavior Service). That is, the model provides functions such as model data query and model data status update, including data and business.
  • View (view) : Responsible for the display of the model, generally the user interface we see, what the customer wants to see.
  • Controller (controller) : Receive user requests, entrust to the model for processing (state change), after processing, the returned model data is returned to the view, which is responsible for displaying. In other words, the controller does the job of a dispatcher.

The most typical MVC model is the model of JSP+Servlet+JavaBean.
Insert picture description here

What is SpringMVC?

  • SpringMVC is a web framework based on the MVC pattern and a module of the Spring framework.
  • It is based on the SpringIOC container and uses the characteristics of the container to simplify its configuration, so SpringMVC and Spring can be directly integrated and used.
  • SpringMVC encapsulates the MVC process, shielding a lot of underlying code, so that developers can more easily and quickly complete Web development based on the MVC model.
  • In general: Spring MVC is a part of Spring Framework, a lightweight web framework based on Java to implement MVC.

Features of SpringMVC :

  • Lightweight, easy to learn
  • Efficient, request response based MVC framework
  • Good compatibility with Spring, seamless integration
  • Convention is better than configuration
  • Powerful functions: RESTful, data validation, formatting, localization, themes, etc.
  • Simple and flexible

Core components in SpringMVC

(1) Front controller: DispactherServlet
(2) Processor mapper: HandlerMapping
(3) Processor adapter: HandlerAdapter
(4) Processor: Handler,
(5) View resolver: ViewResolver
(6) View: Introduction of View
component

  • Front controller: It receives requests and responds to results, which is equivalent to a repeater. It is the core component of the Spring MVC framework. With it, the coupling between other components can be reduced. (No programmer development required)
  • Processor mapper: Find the corresponding processor according to the configured mapping rules (according to the requested URL). (No programmer development required)
  • Processor adapter: Adapt to call a specific processor, and execute the method of processing the request in the processor, and return a ModelAndView object after execution.
  • Processor: (Need manual development by programmers).
  • View resolver: The view resolves based on the passed ModelAndView object, and the real view is resolved based on the view resolution name. (No programmer development required)
  • View: View is an interface, and its implementation class supports different types of views. For example: JSP, freemarker, Thymeleaf, etc.

SpringMVC execution process

Insert picture description here
(1) When the user initiates an HTTP request through the browser, the request goes directly to the front controller DispatcherServlet;
(2) The front controller calls the processor mapper HandlerMapping after receiving the request, and the processor mapper finds the specific Handler according to the requested URL , And return it to the front controller;
(3) The front controller calls the processor adapter HandlerAdapter to adapt and call the Handler;
(4) The processor adapter will call the real processor according to the Handler to process the request and process the corresponding Business logic;
(5) When the processor finishes processing the business, it will return a ModelAndView object to the processor adapter, and the HandlerAdapter returns the object to the front controller; here Model is the returned data object, and View is the logical View .
(6) The front controller DispatcherServlet passes the returned ModelAndView object to the view resolver ViewResolver for resolution, and after the resolution is completed, it returns a specific view View to the front controller. (ViewResolver finds the specific View according to the logical View)
(7) The front controller DispatcherServlet renders the specific view, and responds to the user after the rendering is completed (browser display).

About DispatcherServlet configuration instructions

When using SpringMVC, the first step is to configure DispatcherServlet in web.xml. DispatcherServlet is actually a Servlet, so we can configure multiple DispatcherServlets, which are front controllers. When configuring in the web.xml file, you also need to configure interception matching The request, and the loading of the Springmvc configuration file, and the configuration of the startup sequence, make the servlet start with the startup of the Servlet container. The following is the general configuration of DispatcherServlet:

<!--配置前端控制器-->
    <servlet>
        <servlet-name>DispactherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <!--配置加载Springmvc的配置文件-->
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-config.xml</param-value>
        </init-param>
        <!--配置启动顺序,数字越小启动优先级越高-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispactherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

The file name of the configuration file is specified above, instead of using the default configuration file name, the springmvc-config.xml configuration file is used.
Among them, **.xml can be written in multiple ways.
1. Don't write, use the default value: /WEB-INF/-servlet.xml
2./WEB-INF/classes/springMVC.xml
3. classpath*: springmvc-config. xml
4. Multiple values ​​are separated by commas

About SpringMVC configuration file and common part of annotation explanation

The code is:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--自动扫描指定的包,下面所有注解类交给IOC容器处理-->
    <context:component-scan base-package="com.oldou.controller"/>

    <!--配置注解驱动-->
    <mvc:annotation-driven/>

    <!--配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--前缀-->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!--后缀-->
        <property name="suffix" value=".jsp"/>
    </bean>
    
     <!--配置对静态资源的访问(方式一) 2选1-->
	 <mvc:default-servlet-handler/>  	
	<!--配置对静态资源的访问(方式二) 2选1-->
	<mvc:resources mapping="/js/**" location="/WEB-INF/js/"/>
    <mvc:resources mapping="/img/**" location="/WEB-INF/img/"/>
    <mvc:resources mapping="/css/**" location="/WEB-INF/css/"/>
	
    <!--配置拦截器-->
    <mvc:interceptors>
        <mvc:interceptor>
            <!--/** 包括路径及其子路径-->
            <!--/admin/* 拦截的是/admin/add等等这种 , /admin/add/user不会被拦截-->
            <!--/admin/** 拦截的是/admin/下的所有-->
            <mvc:mapping path="/**"/>
            <!--bean配置的就是拦截器-->
            <bean class="com.oldou.Interceptor.MyInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>

<!--文件上传配置-->
<bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
   <!-- 请求的编码格式,必须和jSP的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1 -->
   <property name="defaultEncoding" value="utf-8"/>
   <!-- 上传文件大小上限,单位为字节(10485760=10M) -->
   <property name="maxUploadSize" value="10485760"/>
   <property name="maxInMemorySize" value="40960"/>
</bean>

</beans>

In the above configuration, the annotation scanning at the Controller layer and the annotation driver support are configured, as well as the view parser, static resource mapper, interceptor, etc., and the upload of files can also be configured.

For <mvc:annotation-driven/>the annotations on the classes in the specified package, the commonly used annotations are as follows:

  • @Controller declares the Controller component, which usually acts on the control layer (such as the Controller of Spring MVC). It is used to identify the class of the control layer as a Bean in Spring, and its function is the same as @Component.
  • @Service declares the Service component @Service("myMovieLister"), which usually acts on the business layer (Service layer) and is used to identify the business layer class as a Bean in Spring, and its function is the same as @Component.
  • @Repository declares the Dao component, and identifies the class of the data access layer (DAO layer) as a Bean in Spring, which has the same function as @Component.
  • @Component refers to components in general. You can use this annotation to describe Beans in Spring, but it is a generalized concept that only represents a component (Bean) and can be applied at any level. When using, just mark the annotation on the corresponding class.
  • @RequestMapping("/menu") request mapping, used to map url to a controller class or a specific handler method. Can be used on classes or methods. Used on classes, it means that all methods in the class that respond to requests use this address as the parent path.
  • @Resource is used for injection, (provided by j2ee) is assembled by name by default, @Resource(name="beanName")
  • @Autowired is used for injection, (provided by srping) is assembled by type by default
  • @Transactional( rollbackFor={Exception.class}) transaction management
  • @RequestBody : Annotation realizes receiving json data of http request and converting json into java object.
  • @ResponseBody : The annotation implementation converts the object returned by the conreoller method into a json object response to the customer.
  • @Scope("prototype") sets the scope of the bean
  • @GetMapping : It is a shortcut of @RequestMapping(method =RequestMethod.GET) and can only handle Get type requests.
  • @PostMapping : It is a shortcut of @RequestMapping(method =RequestMethod.POST) and can only handle Post type requests.
  • @RequestParam : bind the request parameter to the method parameter of the controller
  • @Configuration : Declares that the current class is a configuration class, which is equivalent to the Spring configuration in xml form. This annotation needs to be added to the class.

Wait...There are other comments, so I will organize a blog dedicated to explaining the comments.

Learn from each other and improve each other. This article is a note written when you first learned SpringMVC. Today I turned it out and shared it with you. I hope it will be helpful to you (if you are helpful, I hope to like it and recommend it, thank you). If there are areas that need improvement in the article, please tell me, thank you.

Participation information: https://www.iteye.com/blog/elf8848-875830

Guess you like

Origin blog.csdn.net/weixin_43246215/article/details/108345624