Spring MVC core technology

Posted by sanchez77 on Wed, 09 Feb 2022 00:05:51 +0100

Spring MVC core technology.

4.1 forwarding and redirection

forward: view full path

redirect: view full path

mv.setViewName("forward:/hello.jsp");
mv.setViewName("redirect:/other.jsp");

4.2 exception handling

The framework uses centralized exception handling. Collect the exceptions thrown in each Controller to one place for processing. Exception handlers are called exception handlers.

Two annotations are used in the framework to complete the centralized processing of exceptions. In this way, each controller does not need to handle exceptions separately. The notes are:

1) @ ExceptionHandler: placed above the method, indicating that this method can handle a certain type of exception. This method is executed when an exception occurs.

  1. @ControllerAdvice: placed on the top of the class, indicating that there are exception handling methods in this class. Equivalent to @ Aspect. In aop

@ ControllerAdvice is regarded as Controller enhancement, which is to add exception handling function to Controller class

4.3 interceptor

Interceptor: an object in the spring MVC framework, which needs to implement the interface HandlerInterceptor Intercept user requests. Intercepted the controller's request.

Function: intercept the user's request and process the request in advance. Decide whether to execute the controller according to the processing result. You can also define functions shared by multiple controllers to interceptors.

characteristic:

  1. Interceptors can be divided into system interceptors and user-defined interceptors.
  2. A project can have multiple interceptors. 0, or more custom interceptors.
  3. Interceptors focus on intercepting user requests.
  4. Interceptors are executed before request processing.

Definition of Interceptor:

1) Create a class to implement the interceptor interface HandlerInterceptor and implement the methods in the interface (3)

2) In the spring MVC configuration file, declare the interceptor object and specify the uri address of the interceptor

4.3.1 first interceptor

public class MyInterceptor implements HandlerInterceptor {
    /**
     *  preHandle: A method of pre-processing requests.
     *  Parameters:
     *     Object handler :  Intercepted controller object (MyController)
     *  Return value: boolean
     *   true: The request is correct and can be processed by the controller.
     *     =====MyInterceptor preHandle of interceptor====
     *     The doSome method of MyController is executed
     *     =====MyInterceptor postHandle of interceptor====
     *     =====MyInterceptor After completion of interceptor====
     *   false: The request cannot be processed and the controller method will not execute. The request ends here.
     *     =====MyInterceptor preHandle of interceptor====
     * characteristic:
     *  1. The execution time of the preprocessing method: it is executed before the controller method.
     *  2. You can process requests, check login, judge permissions, statistics, etc.
     *  3. Decide whether to execute the request.
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        System.out.println("=====MyInterceptor Interceptor preHandle====");
        return true;
    }

    /**
     * postHandle: Post processing method
     * Parameters:
     *  Object handler :  Intercepted controller object (MyController)
     *  ModelAndView mv:  Return value of the controller method (execution result of the request)
     *
     * characteristic:
     *  1. Executed after the controller method.
     *  2. The execution result of the controller method can be obtained. The original execution result can be modified.
     *     You can modify the data or the view
     *  3. You can do the secondary processing of the request.
     */
    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object handler,
                           ModelAndView mv) throws Exception {
        System.out.println("=====MyInterceptor Interceptor postHandle====");
    }

    /**
     * afterCompletion: Method of final execution
     * Parameters:
     *   Object handler :  Intercepted controller object (MyController)
     *   Exception ex:  Exception object
     *
     * characteristic:
     *  1. Executed after the request processing is completed,
     *     The sign of request processing completion is that the view processing is completed. After the forward operation is performed on the view.
     *
     *  2. You can do the last work of the program, free memory and clean up temporary variables.
     *
     *  3. Execution conditions of the method:
     *     1)The current interceptor must execute its preHandle() method.
     *     2)preHandle()Must return true.
     */
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler,
                                Exception ex) throws Exception {
        System.out.println("=====MyInterceptor Interceptor afterCompletion====");
    }
}

configuration file

<!--Declaration interceptor-->
<mvc:interceptors>
    <!--Declare first interceptor-->
    <mvc:interceptor>
        <!--Specifies the interception address of the interceptor
            path: Intercepted uri Address, using ** Wildcards.
                  For example: path="/user/**"
                  http://localhost:8080/user/listUser.do
                  http://localhost:8080/user/query/queryUser.do
        -->
        <mvc:mapping path="/**"/>
        <!--Specifies the interceptor to use-->
        <bean class="com.bjpowernode.handler.MyInterceptor"/>
    </mvc:interceptor>

</mvc:interceptors>

When your preHandle returns true, the execution result:

=====MyInterceptor Interceptor preHandle====
Yes MyController of doSome method
=====MyInterceptor Interceptor postHandle====
=====MyInterceptor Interceptor afterCompletion====

Execution order of requests: user some.do---preHandle---doSome---postHandle--afterComplietion

When preHandle returns false

=====MyInterceptor Interceptor preHandle====

4.3.2 multiple interceptors

Two interceptors are used, mainly depending on the execution order of the interceptor and controlling the execution of the request according to one method

1) First interceptor, preHandle=true, second interceptor

=====MyInterceptor111111 Interceptor preHandle====
=====MyInterceptor222222 Interceptor preHandle====
Yes MyController of doSome method
=====MyInterceptor222222 Interceptor postHandle====
=====MyInterceptor111111 Interceptor postHandle====
=====MyInterceptor222222 Interceptor afterCompletion====
=====MyInterceptor111111 Interceptor afterCompletion====

Order of execution of requests:

User some Do - preHandle of interceptor 1 - interceptor 2preHandle - controller doSome - interceptor 2postHandle - postHandle of interceptor 1 - afterCompletion of interceptor 2 - afterCompletion of interceptor 1.

2) Two interceptors, the first preHandle=true and the second preHandle=false

=====MyInterceptor111111 Interceptor preHandle====
=====MyInterceptor222222 Interceptor preHandle====
=====MyInterceptor111111 Interceptor afterCompletion====

3) Two interceptors, the first preHandle=false and the second preHandle=true|false

=====MyInterceptor111111 Interceptor preHandle====

Why use multiple interceptors?

  1. Distribute the verification function to independent interceptors. Each interceptor performs a single verification process.
  2. Combine multiple interceptors.

Summary:

Multiple interceptors, strung on a chain. Multiple interceptors and a controller object are on a chain. The framework uses handler execution chain to represent the execution chain

public class HandlerExecutionChain {
   
    private final Object handler;  // Where the controller object is stored, MyController
    @Nullable
    private HandlerInterceptor[] interceptors; // To store multiple interceptor objects. MyInterceptor 1, 2
    @Nullable
    private List<HandlerInterceptor> interceptorList;
}

How does the interceptor realize the execution order of 1,2,2,1 and traverse the HandlerInterceptor[] interceptors array

HandlerInterceptor[] interceptors = { MyInterceptor1, MyInterceptor2};
//Loop call method 1-2
for(int i=0;i<interceptors.length;i++){
      HandlerInterceptor  obj= interceptors[i];
      obj.preHandle();
}

MyController.doSome();

// 2-1
for(int i=interceptors.length-1 ;i>=0;i--){
      HandlerInterceptor  obj= interceptors[i];
      obj.postHandle();
}

4.3.3 comparison between interceptor and filter

1) Interceptors are objects in the spring MVC framework. Filters are objects in servlet s.

2) The interceptor object is created by the framework container, and the filter object is created by tomcat.

  1. The interceptor can judge and process the request. The filter focuses on setting values for the attributes and parameters of request and response objects. For example, request setCharacterEncoding(“utf-8”)

  2. There are three execution times of the interceptor, before the controller method, after the request is completed. The filter is before the request.

5) Interceptor is used to intercept requests for controller and dynamic resources. Filters can filter all requests, both dynamic and static.

6) Interceptor and filter are executed together. The filter to be executed first is followed by central scheduler, interceptor and controller method