Spring MVC notes from zero to bottom process analysis

1. General

1. SpringMVC:Is based on spring A framework of is actually spring A module that specializes in web Developed, servlet An upgraded version of
    web The bottom layer of development is servlet,The frame is in servlet Add some functions to the foundation for you to do web development

2. SpringMVC Just one spring Container, spring It's a container, ioc Able to manage objects and use <bean> @Component @Repository @Service @Controler
    SpringMVC Can create objects and put them into containers( SpringMVC Container), springmvc The container contains controller objects.

    All we have to do is use @Controller Create a controller object and put the object into springmvc In the container, the created object is used as a controller, and the controller object can
    Accept the user's request and display the processing result as a servlet To use

    use@Cotroller Annotation creates an object of a common class, not servlet. springmvc The controller object is given the following additional functions

    web The bottom layer of development is servlet,springmvc One object in is servlet : DispatchServlet(central scheduler )
    DispatchServlet: Be responsible for accepting all requests from the user, and the user will send the request to DispatchServlet,And then DispatchServlet Put the request
    Forwarded to us Controller Object, and finally Controller Object processing request


3. Process: index.jsp -----DispatchServlet--- Forward, assign to ------- Controller Object, reply

4. advantage:
    1. be based on MVC framework
    2. Easy to understand, quick to use and easy to use
    3. As spring Can be used as part of Spring of IOC and AOP . Easy integration
    4. SpringMVC Strengthen the use of annotations in the controller Service Dao Can be used. Convenient and flexible
        use @Controller Create a processor object,@Service Create business objects,@Autowried perhaps @Resource Inject in controller Service

2. The first spring MVC project

Requirement: the user sends a request to the controller object of spring MVC on the page
And display the processing result of the request

Implementation steps

  1. New web maven project
  2. Join dependency
    spring - webmvc dependency, indirectly adding spin dependency to the project
  3. Key: register the core object DispatcherServlet of spring MVC framework in web.xml
    1. Dispatcher Servlet is called central scheduler. It is a Servlet whose parent class is HTTP Servlet
    2. Dispatcher servlet is also called front Controller
    3. DispatcherServlet is responsible for accepting the submitted request, calling other controller objects, and displaying the processing results of the request to the user
  4. Create an originating request page, index.jsp
  5. Create controller class
    1. Add the @ Controller annotation to the class, create the object, and put it into the spring MVC container
    2. Annotate the method of the class with @ RequestMapping
  6. Create a jsp to display the result of request processing
  7. Create a configuration file for spring MVC
    1. Declare the component scanner and specify the package name where the @ Controller annotation is located
    2. Declare a view parser to help process views

3. Source code analysis of spring MVC execution process:

  1. tomcat starts the process of creating a container
    Create the DispatcherServlet object through the 1 specified by the load on start tag,
    The parent class of DispatcherServlet is HttpServlet, which is a Servlet that executes the init() method when it is created
    In the init() method:
    //Create a container and read the configuration file
    WebApplicationContext ctx = new ClassPathXmlApplication("springmvc.xml");
    //Put the container into the ServletContext
    getServletContext().setAttribute(key,ctx)

The above container is used to create the class object where the @ Controller annotation is located, and create the MyController object,
This object is put into the container of spring MVC, which is a map, similar to map.put("MyController", MyController object)

  1. Processing of requests
    Execute the Service method in the Servlet
        protected void service(HttpServletRequest request,HttpServletResponse response)
        
        protected void doService(HttpServletRequest request,HttpServletResponse response)

        this.doDispatch(request,response){
            // Call the doSome() method of MyController
        }

Sample code

Web.xml configuration file

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
<!--    Statement. register springmvc Core object of DispatcherServlet
        After the server starts, you need to create DispatcherServlet Object
        Why?
            because DispatcherServlet In the process of creating it, it will be created at the same time springmvc Container object
            read springmvc The objects of this configuration file are all created. When the user initiates a request, it can be used directly
            Use object

        Servlet Initialization will be performed init() method. DispatcherServlet stay inti() in
        Create a container, read the configuration file, and put the container object into the ServletContext
        webApplicationContext ctx = ClassPathXmlApplication("Spring.xml");

        // Put the container into the ServletContext
        getServletContext().setAttribute(key,ctx);
-->
    <servlet>
        <servlet-name>myweb</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<!--        Custom in mvc Rules for reading files in-->
        <init-param>
<!--            custom springmvc Properties of the configuration file-->
            <param-name>contextConfigLocation</param-name>
<!--            Specifies the path to the customization file-->
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
<!--        stay tomcat Create after startup Servlet object-->
<!--        express tomcat The order in which objects are created after startup. Its value is an integer. The smaller the value, the earlier the object is created-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>myweb</servlet-name>
<!--
    When using frames, url-pattern Two values can be used
    1. Using extension method, syntax:*.xxx,xxxx Is a custom extension. Common way *.do,*.action *.mvc etc.
        http://localhost:8080/myweb/some.do . . . 
    2. Use slash
-->
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
</web-app>

springmvc.xml configuration file

<?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"
       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">
<!--    Declaration component scanner-->
    <context:component-scan base-package="com.lcx.controller"/>
<!--    The view parser helps developers set the path of the view file-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--        Prefix: path to view file-->
        <property name="prefix" value="/WEB-INF/view/"/>
<!--        suffix-->
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

Controller class

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * @Controller Create a processor object and place it in the spring MVC container
 * Location: above the class
 * And spring are @ Component
 */
@Controller
public class MyController {
    /*
    * Spring MVC uses methods to handle requests submitted by users
    * Methods are user-defined, and can have multiple return values, multiple parameters, and method names
    * */


    /**
     * Prepare to use dosome to handle some.do requests
     * @RequestMapping:Request mapping is used to bind a request address to a method,
     *                  A request specifies the processing of a method
     *              Attribute: 1. value is a string indicating the URL address of the request
     *                  value Must be unique and cannot be repeated. It is recommended to start with "/" when using
     *              Position: 1. Above the method
     *                   2. Above the class
     *          Note: the method modified by RequestMapping is called processor method or controller method.
     *          The method decorated with @ RequestMapping can handle requests, similar to doGet doPost in Servlet
     *
     * Return value: ModeLAndView
     *      Model: Data, the data to be displayed to the user after the request processing is completed
     *      view: Views, such as jsp and so on.
     */
    @RequestMapping(value = "/some.do")
    public ModelAndView doSome(){        // Doget() -- service request processing
        //
        ModelAndView mv = new ModelAndView();
        // Add data, and the framework puts the data into the Request scope at the end of the Request
        mv.addObject("msg","Hello World");
        mv.addObject("fun","Executive doSome method");
        //Specify view
        // forward operation performed by the framework on the view, Request.getRequestDispatcher(...).forward()
        // mv.setViewName("/show.jsp");
        // Return mv
        // When the view parser is configured, you can use the logical name (file name) to specify the view
        // The framework will use the prefix + logical name + suffix of the view parser to form a full path. Here is the character connection operation
        mv.setViewName("show");
        return mv;
    }
}

JSP file

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>show.jsp</h1>
    <h2>msg data:${msg}</h2>
    <h2>fun data:${fun}</h2>

</body>
</html>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <P>first springmvc project</P>
    <p><a href="/SpringMVC_hello_war_exploded/some.do">launch some.do request</a> </p>
</body>
</html>

3. Annotation oriented development

1. @RequestMapping define request rules

1. @RequestMapping When used above a class, this prefix is added to each address in the method in the class
2. @RequestMapping Specify a specific request method (no writing means all requests are accepted) : Request mapping
        Properties: method Indicates the method of the request and its value RequestMethod Class enumeration
                    RequestMethod.GET;
                    ....

Parameters of processing method

Processor methods can contain the following four types of parameters, which will be automatically assigned by the system during system call and can be used directly
    1. HttpServletRequset
    2. HttpServletResponse
    3. HttpServletSession
    4. Request parameters carried in the request
public ModeAndView doSome(HttpServletRequest req,HttpServletResponse res,HttpSession session){}

Receive user's parameters

1. Receive one by one: the formal parameter name of the processor method must be consistent with the parameter name in the request, and the request parameter with the same name is assigned to the formal parameter with the same name
    be careful:
        stay post When submitting Chinese, Chinese garbled code will appear. At this time, reason filter is needed to solve the garbled code problem

Spring MVC has its own filter to solve post garbled code

<filter>
    <filter-name>filerName</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>utf-8</param-value>
    </init-param>
    <init-param>
        <param-name>forceRequestEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
    <init-param>
        <param-name>forceResponseEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
    <filter-mapping>
    <filter-name>filerName</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Spring MVC implements the filter source code. It can be seen that whether to set encoding is determined by forceRequestEncoding and forceResponseEncoding

protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String encoding = this.getEncoding();
        if (encoding != null) {
        if (this.isForceRequestEncoding() || request.getCharacterEncoding() == null) {
        request.setCharacterEncoding(encoding);
        }

        if (this.isForceResponseEncoding()) {
        response.setCharacterEncoding(encoding);
        }
        }

        filterChain.doFilter(request, response);
        }
    @RequestParam : Solve the problem of different parameter names and formal parameter names in the request
        Properties: value Parameter name in request
             require It's a boolean The default is true Indicates that this parameter must be included in the request
             produces: Use this property to define a new contentType
        Location: in front of the parameter definition of the processor method
public ModeAndView receiveParam(@RequestParam("rname") String name
                                @RequestParam("rage") Integer age){}
2. Object reception: Using java Object to accept parameters
    The processor method parameter is java Object whose property name is the same as the parameter name in the request
    Frame or to create a parameter java Object, assign a value to the attribute, and the request parameter is name Will call setName

3. Return value of processing method
    1. return ModeAndView
        If the processor method needs to jump to other resources and transfer data between the jumped resources after processing, then
        Processor method return ModeAndView Better. Of course, if you want to return ModeAndView,Processor method
        Need to be defined in ModeAndView object
    2. return String
        The string returned by the processor method can specify the logical view name, which can be converted to the physical view address by the view parser
        The framework performs a forwarding operation
    3. return void
        It cannot represent data or view. It is in processing ajax Use when void return. adopt HttpServletResponse Output data.
        response ajax Request. ajax The request returns data, independent of the view
    4. return Object
        Processing methods can also return Object Object, this Object Can be Integer,String Custom objects, Map,list
        And so on, but the returned object does not appear as a logical view, but as data displayed directly on the page.
        Return object, need to use @ResponseBody Annotation, the converted JSON Put the data into the response body
        
        Implementation steps:
            1. join json Tool library dependency, springmvc Default use jackson
            2. stay springmvc Join between profiles <mvc:annotation-driven> Annotation driven
            3. Add on top of the processor @ResponseBody annotation

        principle:
            springmvc When an object is returned, it can be converted to json Output to browser, response ajax Internal and Arnie
            1. <mvc:annotation-driven> Annotation driven
                The function of annotation driven implementation is to complete java Object to json xml text Conversion of binary and other data formats
                HttpMessageConveter Interface: message converter.
                Function: defined java Turn into json,xml And other data formats. This interface has many implementation classes
                        These implementation classes are complete java Many objects json,java Object to xml ,java Object to binary data conversion

        @RequestBody annotation
                Framework processing flow:
                1. The framework will return this object and call the ArrayList<HttpMessageConverter> For each class in canWrite()method
                Check that HttpMessageConverter The implementation class of the interface can handle Student Type of data
                2. The framework calls the implementation class write(),MappingJackson2HTTPMessageConvert of writ() Method, the object to be returned
                Convert to json Diao Hong jackson of objectMapper Implement conversion to json contenType: Application/json;chartset=utf-8
                3. The framework will call @RespinseBody Output the results of 2 to the browser.

        When the returned value is List Will be converted to JsonArray
        When there @RequestBody When annotation, the return value is String Will be automatically converted to json format

Processing method of static resources

When set url-pattren -Setting the of the central scheduler url-pattern yes */* It will cause static resource access failure
 The first solution to static resource access: in springmvc In the configuration file <mvc:default-servlet-handler> 
    Principle: add a processor object to the program memory, DefaultHttpRequestHandler,Let this object handle static resources
 The second static resource processing method:<mvc:resource mapping="/static/**" location="/static/"/>

4. Spring MVC core technology

4.1 request redirection and forwarding

    When the processor jumps to other resources after processing the request, there are two jump methods: request forwarding and redirection.
According to the resource type to jump, it can be divided into two categories: jump to page and jump to other processors.
    However, for the page requesting forwarding, it can be WEB-INF But the redirection cannot be the page under this because the user is
 You cannot directly access the resources under this path

SpringMVC take servlet The request forwarding and redirection in are encapsulated
forward: Indicates forwarding
redirect: Indicates redirection
forward:
    Return from processor method ModeAndView Realize forwarding forward
    grammar: setViewName("forward:View file full path")
    forward Features: it is not used with view parser, just as there is no view parser in the project. The path used to forward parsers that are not in the view
redirect:
    It is not used with the view parser, just as there is no view parser in the project
    Will you Mode The simple data in is converted to a string and converted to string Use, redirect request parameters

4.2 exception handling

The spring MVC framework is a common way to handle exceptions, using the @ ExceptionHandler annotation to handle exceptions

4.2.1 @ExceptionHandler annotation

    Using annotations @ExceptionHandler You can specify a method as an exception handling method. The annotation has only one optional attribute value,For one Class<?> array
 Used to specify the exception to be handled by the annotated method, that is, the exception to be matched.
    The return value of the annotated method can be ModeAndView String or void The method name is optional, and the parameters of the method can be Exception And its subclass objects
HTTPServiceRequest,HTTPServiceResponse Wait. The system automatically assigns values to these method parameters
    For the usage of exception handling annotation, you can also directly associate the exception handling method annotation with Controller in

Unified global exception handling

Centralize all exception handling in the Controller in one place, the idea of AOP, and reduce coupling
Exception handling steps

  1. Create maven web project
  2. Join dependency
  3. Create a custom exception class, MyUserException, and define its subclasses NameException and AgeException
  4. Throw this exception in the Controller
  5. Create a general class to function as a global exception handling class
    1. Add ControllerAdvice to the class
    2. Define the method in the class, and add @ ExceptionHandler above the method
  6. Create a view interface for handling exceptions
  7. Create spring MVC configuration file
    1. Component scanner, scanning @ Controller annotations
    2. The component scanner scans the package name of @ ControllerAdvice
    3. Declarative annotation driven

@ControllerAdvice: controller enhancement (adding functions to the controller - exception handling)
Features: the framework must know the package name of this annotation, and the component scanner needs to be declared in the spring MVC configuration file
Specify the method where @ ControllerAdvice is located

The exception handling method is the same as the definition of the controller method. It can have multiple parameters and multiple return values, such as ModeAndView, String, void, etc

Formal parameter: Exception, indicating the Exception object thrown in the Controller
The exception information can be obtained through formal parameters

@Exceptionhandler (class of exception): indicates the type of exception. When this type of exception is sent, it is handled by the current method

Exception handling logic:
1. It is necessary to record the exceptions to the database and log file
Record the time, which method occurred, and the exception error content
2. Send notice
3. Give user-friendly tips

4.3 interceptor

SpringMVC Medium Interceptor Interceptor is very important and useful. Its main function is to intercept specified user requests and carry out corresponding preprocessing and post-processing
 The interception time point is"Processor mapping maps out the processor class to be executed according to the request submitted by the user, and also finds the processor adapter to specify the processor class to be changed,
Before the processor adapter executes the processor",Of course, when the processor maps out the processor class to be executed, the interceptor and the processor have been linked to one processor execution chain,
And return to the central scheduler.

1. Need to implement HandlerInterceptor Interface
2. Interceptors are similar to filters, but filters are mainly used to filter request parameters and set coded character sets
3. Interceptors are global and can be used for multiple Controller Do interception
    Multiple interceptors can exist in a project, which are generally used in user login processing, permission checking and logging

4.3.1 execution of an interceptor

Interceptor usage steps

  1. Defines a class that implements the HandlerInterceptor interface
  2. Declare interceptors in the spring MVC configuration file.

execution time

  1. Intercepted before the method in the Controller class executes
  2. The interceptor is also executed after the controller method is executed
  3. The interceptor is also executed after the request is processed
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyInterceptor implements HandlerInterceptor {
    /**
     * preHandel It is called pretreatment method
     * characteristic:
     *  1. Method is executed before the controller method (doSome of MyController)
     *      The method by which the user's request first arrives
     *  2. In this method, you can obtain the requested information and verify whether the request meets the requirements
     *      You can verify that the user has permission to connect to an address
     *      If the verification fails, the request can be truncated and cannot be processed
     *      If the verification is successful, the request can be released, and then the controller method can be executed.
     * @param handler Intercepted controller object
     *
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle");
        return true;  // If it is true, it will be released; if it is false, it will not be released
    }


    /**
     * Post processing method
     *
     * Features: it is executed after the doSome method of the Controller, and the return value of the processor method can be obtained
     *      ModeAndView,You can modify the data and view in ModeAndView, which can affect the final execution result
     *      It is mainly to make a secondary correction to the results
     *
     * @param request
     * @param response
     * @param handler   Controller object executed by interceptor
     * @param modelAndView  Return value of processing method
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");
    }

    /**
     * Method of final execution
     *
     * characteristic:
     * 1,Execute after request processing is completed. In the framework, when the view processing is completed, forward is executed on the view. It is considered that the request processing is completed.
     * 2,Generally, do resource recovery and recycle the occupied memory
     * @param request
     * @param response
     * @param handler   Intercepted Controller processing object
     * @param ex        An exception occurred in the program
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion");
    }
}

Interceptor: as a common function in multiple controllers, it is the idea of AOP

Execution sequence of multiple interceptors

An ArrayList collection is saved in the framework, so it is stored in the order of configuration
For example, if there are two interceptors, the order of execution is
1-1 -- > 2-1 -- > 2-2 -- > 1-2 -- > 2-3 -- > 1-3 (the first number represents the interceptors and the second number represents the corresponding three methods)
If the first is true, the second is false
1-1 --> 2-1 --> 1-3
When the first is false, none of the following methods will be executed

The difference between interceptors and filters

  1. Filters are objects in servlet s and interceptors are objects in frameworks.
  2. The Filter is the training Filter interface object, and the interceptor is the implementation of HandlerInterceptor
  3. The filter is used to set the parameters and properties of request and response, focusing on data filtering. Interceptors are used to validate requests
  4. Filtering is performed before the interceptor
  5. The filter is the object created by tomcat server, and the interceptor is the object created by spring MVC
  6. The filter is an execution time point, and the interceptor has three execution time points
  7. The filter can handle jsp, js, html, etc. the interceptor is the Controller object. If the request is not accepted by the central scheduler, the intercepted content will not be executed
  8. The interceptor intercepts the execution of common class methods, and the filter filters the Servlet request response

4.4 spring MVC processing flow

1. User initiated request
2. DispatcherServlet Receive the request and give the object to the processor mapper
    Processor mapper: SpringMVC A kind of object in which the framework takes matters into account HandleMapping Classes of interfaces are called mappers
    The role of the processor mapper: on request, from SprintMVC Get processing object from container object( ctx.getBean("beanName"));
    The framework places the found processor objects into a called processor execution chain( HandlerExecutionChain)Class save
    HandlerExecutionChain Class: 1. Processor object( MyController)2. All interceptors in the project List<HandlerIntercept>
3. DispatcherServlet Put the in 2 HandlerExecutionChain The processing object in was handed over to the processor adapter object (s)
    Processor adapter: springMVC Objects in need of implementation HandlerAdapter Interface
    The role of the processor adapter is to execute processor methods (calls) MyController.doSome()Get return value ModeAndView)
4. DispatcherServlet Put the data obtained in 3 ModeAndView Object to view parser
    View parser object: springMVC Objects in need of implementation ViewResoler Interface (can have multiple)
    The function of view parser: compose the complete path of the view, use prefix and suffix, and create view object
        view Is an interface that represents the view in the framework jsp,html Not with string Instead of using view And his implementation classes represent views
        InternalResourceView: View class, representing jsp File, the view parser creates InternalResourceView Class object
        Inside this object, there is a property, which is url 
5. DispatcherServlet Put the in step 4 view Object get, call view Class to render itself, fill in data, and form a response object
6. Central scheduler response browser

Core method DispatcherServlet.doDispatch()

Tags: Java Spring mvc

Posted on Fri, 29 Oct 2021 12:04:05 -0400 by bacarudaguy