Introduction to spring MVC framework 60-72: interceptors

Start time: February 22, 2022
Node: MVC curriculum

Interceptor

Interceptor:
1) Interceptor is a kind of spring MVC, which needs to implement the HandlerInterceptor interface.
2) Interceptors are similar to filters, with different functional directions and emphases. Filters are used to filter request parameters and set coded character sets.
The interceptor intercepts the user's request and makes judgment.
3) The interceptor is global and can intercept multiple controllers.
There can be 0 or more interceptors in a project, which together intercept users' requests.
Interceptors are commonly used in: user login processing, permission checking and logging.

Use steps of Interceptor:
1. Define a class to implement the HandlerInterceptor interface
2. In the spring MVC configuration file, declare the interceptor to let the framework know the existence of the interceptor.

Execution time of Interceptor:
1) Before the request is processed, that is, before the method in the controller class is executed, it is intercepted.
2) The interceptor is also executed after the controller method is executed.
3) The interceptor is also executed after the request is processed.

Interceptor: regarded as a common function in multiple controllers, it is centralized to the interceptor for unified processing. Using the idea of aop

Interceptor usage steps

1. Create a new maven web project
2. Join dependency
3. Create Controller class
4. Create a common class to be used as an interceptor
1) Implement HandlerInterceptor interface
2) Implement three methods in the interface
5. Create show jsp
6. Create spring MVC configuration file
1) Component scanner, scanning @ Controller annotations
2) Declare the interceptor and specify the uri address of the intercepted request

Write in this order
MyController class

public class MyController {
    @RequestMapping(value = "/some.do")
    public ModelAndView doSome(String name, Integer age) {
        System.out.println("=====implement MyController Medium doSome method=====");
        //Process some Do requested. It is equivalent to that the service call processing is completed.
        ModelAndView mv = new ModelAndView();
        mv.addObject("myname", name);
        mv.addObject("myage", age);
        mv.setViewName("show");
        return mv;
    }
}

Create interceptor

package BUPT.handler;

import...;

//Interceptor class: intercepts user requests.
public class MyInterceptor implements HandlerInterceptor {

    //private long btime = 0;
    /*
     * preHandle It is called pretreatment method.
     *   Important: it is the entrance and portal of the whole project. When preHandle return true Requests can be processed.
     *        preHandle return falseļ¼ŒThe request ends at this method.
     * Parameters:
     *  Object handler :  Intercepted controller object
     * Return value boolean
     *   true: The request is verified by the interceptor and the processor method can be executed.
         *   Interceptor MyInterceptor of preHandle()
             =====implement MyController Medium doSome method=====
             Interceptor MyInterceptor of postHandle()
             Interceptor MyInterceptor of afterCompletion()
         *
     *   false: If the request fails to pass the verification of the interceptor, the request ends when it reaches the interceptor. The request was not processed
     *      Interceptor MyInterceptor of preHandle()

     *  characteristic:
     *   1.Method in controller method( MyController of doSome)Previously executed.
     *     The user's request first arrives at this method
     *
     *   2.In this method, you can obtain the requested information and verify whether the request meets the requirements.
     *     You can verify whether the user logs in and whether the user has permission to access a connection address( url). 
     *      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.
     */

Pretreatment method

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //btime = System.currentTimeMillis();
        System.out.println("Interceptor MyInterceptor of preHandle()");
        //The business logic of the calculation returns true or false according to the calculation result

        return true;
    }

The preprocessing method returns false
At this point, you can only go to tip instead of forwarding it to dosome

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //btime = System.currentTimeMillis();
        System.out.println("Interceptor MyInterceptor of preHandle()");
        //The business logic of the calculation returns true or false according to the calculation result
        //Give the browser a return result
        request.getRequestDispatcher("/tips.jsp").forward(request,response);
        return false;
    }

Post processing method: it is mainly to make secondary correction to the original execution result
Forwarded to other view

    /*
       postHandle:Post processing method.
       Parameters:
        Object handler: Intercepted processor object MyController
        ModelAndView mv:Return value of processor method

        characteristic:
         1.Executed after the processor method (MyController.doSome())
         2.You can get the return value of the processor method ModelAndView, and you can modify the value in ModelAndView
         Data and views can affect the final execution results.
         3.It is mainly to make secondary amendments to the original implementation results,

         ModelAndView mv = MyController.doSome();
         postHandle(request,response,handler,mv);
     */
    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object handler, ModelAndView mv) throws Exception {
        System.out.println("Interceptor MyInterceptor of postHandle()");
        //The original doSome execution results need to be adjusted.
        if( mv != null){
            //Modify data
            mv.addObject("mydate",new Date());
            //Modify view
            mv.setViewName("other");
        }
    }

The last method executed is afterCompletion
characteristic:
1. Executed after the request processing is completed. The framework stipulates that when your view processing is completed, you execute forward on the view. It is considered that the request processing is completed.
2. Generally, for resource recovery, some objects are created in the process of program request, which can be deleted here to recover the occupied memory

    /*
      afterCompletion:Method of final execution
      parameter
        Object handler:Intercepted processor object
        Exception ex: An exception occurred in the program
  . 
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {
        System.out.println("Interceptor MyInterceptor of afterCompletion()");

        //long etime = System.currentTimeMillis();
        //System.out.println("calculate the time from preHandle to the completion of request processing:" + (etime - btime));
    }
}

We get results here

Calculate from preHandle Time to request processing completion: 199

show.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h3>/WEB-INF/view/show.jsp from request Get data from scope</h3><br/>
    <h3>myname Data: ${myname}</h3><br/>
    <h3>myage Data: ${myage}</h3>
</body>
</html>

configuration file
Component scanner

<?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 https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--Declaration component scanner-->
    <context:component-scan base-package="BUPT.controller" />

    <!--statement springmvc The view parser in the framework helps developers set the path of view files-->
    <bean  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--Prefix: path to view file-->
        <property name="prefix" value="/WEB-INF/view/" />
        <!--Suffix: extension of the view file-->
        <property name="suffix" value=".jsp" />
    </bean>

Declaration interceptor

    <!--Declare interceptors: interceptors can have 0 or more-->
    <mvc:interceptors>
        <!--Declare first interceptor-->
        <mvc:interceptor>
            <!--Specify blocked requests uri address
                path: namely uri Address, wildcards can be used **
                      ** :  Represents arbitrary characters, files, or files in multi-level directories and directories
                http://localhost:8080/myweb/user/listUser.do
                http://localhost:8080/myweb/student/addStudent.do
                user Intercept the beginning
            -->
            <mvc:mapping path="/**"/>
            <!--Declare interceptor object-->
            <bean class="BUPT.handler.MyInterceptor" />
        </mvc:interceptor>
    </mvc:interceptors>

</beans>

The order of execution can be observed

Interceptor MyInterceptor of preHandle()
=====implement MyController Medium doSome method=====
Interceptor MyInterceptor of postHandle()
Interceptor MyInterceptor of afterCompletion()

Multiple interceptors

Define another interceptor, MyInterceptor2
The execution order is based on the configuration order in spring MVC
Because the returned is an ArrayList, the order is the configuration order

package BUPT.handler;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

//Interceptor class: intercepts user requests.
public class MyInterceptor2 implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("22222-Interceptor MyInterceptor of preHandle()");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object handler, ModelAndView mv) throws Exception {
        System.out.println("22222-Interceptor MyInterceptor of postHandle()");
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {
        System.out.println("22222-Interceptor MyInterceptor of afterCompletion()");
    }
}

And register him

    <mvc:interceptors>
        <!--Declare first interceptor-->
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <!--Declare interceptor object-->
            <bean class="BUPT.handler.MyInterceptor" />
        </mvc:interceptor>
        <!--Declare a second interceptor-->
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <bean class="BUPT.handler.MyInterceptor2" />
        </mvc:interceptor>
    </mvc:interceptors>

At this time, both the preHandle interceptors are true
Get running results

111111-Interceptor MyInterceptor of preHandle()
22222-Interceptor MyInterceptor of preHandle()
=====implement MyController Medium doSome method=====
22222-Interceptor MyInterceptor of postHandle()
111111-Interceptor MyInterceptor of postHandle()
22222-Interceptor MyInterceptor of afterCompletion()
111111-Interceptor MyInterceptor of afterCompletion()

The execution sequence is shown in the figure

Consider the situation
Interceptor 1 is true and 2 is false

111111-Interceptor MyInterceptor of preHandle()
22222-Interceptor MyInterceptor of preHandle()
111111-Interceptor MyInterceptor of afterCompletion()

Consider the situation
Interceptor 1 is false and 2 is true / false

111111-Interceptor MyInterceptor of preHandle()

As long as a preHandle() method returns false, the upper execution chain will be broken,
Its subsequent processor methods and postHandle() methods will not be executed. However, no matter how the execution chain is executed, as long as
There are methods in the method stack, that is, as long as the preHandle() method returns true in the execution chain, the methods in the method stack will be executed
afterCompletion() method. Will eventually give a response.

The difference between interceptor and filter

The difference between interceptor and filter

1. The filter is the object in the servlet, and the interceptor is the object in the framework

2. The Filter implements the object of the Filter interface, and the interceptor implements the HandlerInterceptor

3. Filter is used to set the parameters and attributes of request and response, focusing on data filtering.
Interceptors are used to verify requests and can truncate requests.

4. The filter is executed before the interceptor.

5. The filter is an object created by the tomcat server
Interceptors are objects created in the spring MVC container

6. The filter is an execution time point.
The interceptor has three execution time points

7. The filter can handle jsp, js, html and so on
Interceptors are objects that focus on intercepting the Controller. If your request cannot be received by the dispatcher servlet, the request will not execute the interceptor content

8. The interceptor intercepts the execution of ordinary methods, and the filter filters the servlet request response

Login authentication interceptor

CH12 interceptor permission: use the interceptor to check whether the logged in user can access the system

Implementation steps:
1. New maven
2. Modify web XML register central scheduler
3. Create a new index JSP initiate request
4. Create MyController to process requests
5. Create the result show jsp
6. Create a login JSP, simulate login (put the user's information into the session);
Create a jsp, logout jsp, simulate exiting the system (delete data from the session)
7. Create an interceptor, obtain the user's login data from the session, and verify whether the system can be accessed
8. Create a validated jsp and give a prompt if the view is validated
9. Create spring MVC configuration file
Declaration component scanner
Declaration interceptor

I want to explain this function
That is to say
At first, if I input my name and age directly on the index interface
No matter whether the name I input is zs or not, I can't go in, because the judgment logic here is whether there is zs in the session

And when I type directly in the browser
http://localhost:8080/ch12_interceptor_permission/login.jsp
Entered login JSP, which simulates the login success (the login success here does not come from the index, but the URL entered directly)
here
When I get to the index interface again, no matter whether the input is zs or not, I can go in and get the information
It is equivalent to entering login once and obtaining administrator permission. You can operate at this time

If you want to cancel the permission, enter it in the browser
http://localhost:8080/ch12_interceptor_permission/logout.jsp
In this way, you can't enter anything from the index

A lot of code is repetitive
Here are some non repetitive ones
MyInterceptor

package BUPT.handler;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

//Interceptor class: intercepts user requests.
public class MyInterceptor implements HandlerInterceptor {
    //Verify that the logged in user information is correct, return true, and other return false
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("111111-Interceptor MyInterceptor of preHandle()");
        String loginName = "";
        //Get the value of name from session
        Object attr  = request.getSession().getAttribute("name");
        if( attr != null){
            loginName = (String)attr;
        }

        //Judge whether the login account meets the requirements
        if( !"zs".equals(loginName)){
            //Unable to access the system
            //Prompt the user
            request.getRequestDispatcher("/tips.jsp").forward(request,response);
            return false;
        }
        //zs login
        return true;
    }
}

login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    Simulate login,zs Login system
    <%
        session.setAttribute("name","zs");
    %>

</body>
</html>

logout.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
   Exit the system from session Delete data from
  <%
      session.removeAttribute("name");
  %>
</body>
</html>

tips.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
  tips.jsp  wrong zs Unable to access the system
</body>
</html>

First visit




Then let it log in once



Quit again

You can't go in

Summarize spring MVC process


(1) The browser submits the request to the central scheduler (some. Do in index.jsp)
(2) The central scheduler forwards the request directly to the processor mapper.
(3) The processor mapper will find the processor that handles the request according to the request and encapsulate it as the processor execution chain
Return to the central scheduler. (dosome in MyController)
(4) The central scheduler finds the processor adapter that can execute the processor according to the processor in the processor execution chain.
(5) The processor adapter calls the execution processor.
(6) The processor encapsulates the processing result and the view to jump into an object ModelAndView, and returns it to the
Processor adapter. (doSome returns mv)
(7) The processor adapter returns the result directly to the central scheduler.
(8) The central scheduler calls the view parser to encapsulate the view name in ModelAndView as a view object.
(9) The view parser returns the encapsulated view object to the central scheduler (the view parser in springmvc.xml)
(10) The central scheduler calls the view object and lets it render by itself, that is, data filling to form a response object.
(11) The central scheduler responds to the browser. (show.jsp)

Or
Processing flow of spring MVC internal request:

  • User initiated request some do
  • Dispatcher servlet receives request some Do, forward the request to the processor mapper
  • Processor mapper: an object in the spring MVC framework. The framework calls all classes that implement the HandlerMapping interface mapper (multiple)
    Processor mapper function; According to the request, obtain the processor object (MyController controller=ctx.getBean("some.do") from the spring MVC container object, and the framework saves the found processor object in a class called handler execution chain
    The handler executionchain class holds the processor object (MyController) and all interceptors in the project list < handlerinterceptors >
  • DispatcherServlet gives the processor object in HandlerExecutionChain in 2 to the processor adapter object (multiple)
    Processor adapter: an object in the spring MVC framework, which needs to implement the HandlerAdapter interface
    Adapter function: execute the processor method (call MyControllerl.doSome() to get the return value ModelAndView)
  • The dispatcher servlet gives the ModelAndView obtained in 3 to the view parser object
    View parser: the objects in spring MVC need to implement the viewresolver interface (there can be multiple)
    Function of view parser: compose the complete path of the view, using prefix and suffix. And create a view object.
    View is an interface that represents the view. In the framework, JSP and HTML are not represented by string, but by view and its implementation classes.
    InternalResourceView: a view class that represents a jsp file. The view parser will create an InternalResourceView class object.
    This object has a property url = / WEB-INF / view / show jsp
  • The dispatcher servlet obtains the view object created in step 4, calls the view class's own method, and puts the Modiel data into the request scope. Execute the forward of the object view. End of request.

End time: February 23, 2022

Keywords: Java Back-end

Added by php_guy on Wed, 23 Feb 2022 18:11:13 +0200