SpringMVC core technology-interceptor

The Interceptor interceptor in SpringMVC is very important and quite useful. Its main function is to intercept specified user requests and perform corresponding pre-processing and post-processing . The interceptor is global and can intercept multiple Controllers. There can be 0 or more interceptors in a project, and they intercept user requests together. Interceptors are commonly used in: user login processing, permission checking, and logging.

1. The execution of an interceptor

        Implementation steps:

            1. Create the Controller class

            2. Create a common class

                1) Implement the HandleInterceptor interface

                2) Implement the three methods in the interface

            3. Create a show page

            4. Create Springmvc configuration file

                1) Component scanner, scan @Controller annotation

                2) Declare the interceptor and specify the intercepted request uri address

When creating a common class to implement the HandleInterceptor interface, the three methods are explained in detail :

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器方法preHandle()执行");
        return true;
}

preHandle:   preprocessing method

parameter:

         Object handler : the intercepted controller object myController

      The return value is Boolean:

               1. true: the request has passed the verification of the interceptor and the processor method can be executed

        2. False: the request does not pass the verification of the interceptor, and the processor method cannot be executed

Features :

        1. The user's request that is executed before the controller method is executed (myController method) first arrives at this method

       2. In this method, you can obtain the requested information , verify whether the request meets the requirements , verify whether the user is logged in , and verify whether the user has the authority to access a certain link address (url)  .

            If the verification fails, the request can be truncated and the request cannot be processed.

            If the verification is successful, the request can be released, and then the controller method can be executed.

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        time = System.currentTimeMillis();
        if(modelAndView !=null){
            modelAndView.addObject("mydate",new Date());
            modelAndView.setViewName("other");
        }
        System.out.println("拦截器方法postHandle()执行");
}

   postHandle : post-processing method

  Parameters :

           Object handler: the  intercepted processing object myController

           ModelAndView: modelAndView: the return value of the processor method

 Features:

       1. Executed after the processor method (myController.dosome())

       2, the processor may acquire the return value ModelAndView, can modify the data and views ModelAndView , can affect the final execution result.        

       3. Its main function: is to perform a second correction to the original execution result

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("postHandle到afterCompletion方法的执行时间:"+(System.currentTimeMillis()-time));
        System.out.println("拦截器的afterCompletion()执行了");
}

 afterCompletion: the last executed method

Parameters :

       Object handler: the intercepted controller object myController

       Exception ex: the exception that occurred in the program

Features:

       1. Executed after the request processing is completed, the framework stipulates that when your view processing is completed, the request processing is considered complete after you execute the forward on the view

       2. Generally do the work of resource recovery. Some objects are created in the process of program request, and they can be deleted and recycled here.

Create Springmvc configuration file:

      Declare interceptors: there can be 0 or more interceptors

      The first statement interceptor a interceptor interceptor is a

      mapping path="" Specify the intercepted request url address

      path: is the uri address, wildcards can be used **

      **: Represents any character, file or multi-level directory and file in the directory  /user/**: This will be intercepted if it starts with user

      /user: The preceding / is the root directory

<?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 http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
        <context:component-scan base-package="cn.com.Ycy.Contrller"/>
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <!-- 前缀名:视图文件的路径-->
            <property name="prefix" value="/WEB-INF/"/>
            <!-- 后缀名:视图文件的扩展名 -->
            <property name="suffix" value=".jsp"/>
        </bean>
        <!--  声明拦截器:拦截器可以有0个或者多个  -->
        <mvc:interceptors>
            <!-- 声明第一个拦截器 一个interceptor就是一个拦截器 -->
            <mvc:interceptor>
                <mvc:mapping path="/user/**"/>
                <bean class="cn.com.Ycy.handler.myInterceptor"/>
            </mvc:interceptor>
        </mvc:interceptors>
</beans>

  Code demo:

  page:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta http-equiv="Content-Type" content="textml; charset=UTF-8">
    <title>Title</title>
</head>
<body>
    <p>一个拦截器</p>
    <form action="user/some.do" method="post">
        姓名:<input type="text" name="name"><br/>
        年龄:<input type="text" name="age"><br/>
        <input type="submit" value="提交请求">
    </form>
</body>
</html>

Controller class:

@RequestMapping(value = "/user")
@Controller
public class myController {
    @RequestMapping(value = "/some.do")
    public ModelAndView dosome(String name,String age)  {
        System.out.println("dosome方法执行");
        ModelAndView mv = new ModelAndView();
        mv.addObject("myname",name);
        mv.addObject("myage",age);
        mv.setViewName("show");
        return mv;
    }
}

Interceptor class  :

public class myInterceptor implements HandlerInterceptor {
    private long time;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器方法preHandle()执行");
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        time = System.currentTimeMillis();
        if(modelAndView !=null){
            modelAndView.addObject("mydate",new Date());
            modelAndView.setViewName("other");
        }
        System.out.println("拦截器方法postHandle()执行");
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("postHandle到afterCompletion方法的执行时间:"+(System.currentTimeMillis()-time));
        System.out.println("拦截器的afterCompletion()执行了");
    }
}

The execution sequence of the method and the processor method in the interceptor is as follows:

       2. The execution of multiple interceptors

       When there are multiple interceptors, an interceptor chain is formed . The execution order of the interceptor chain is consistent with its registration order. It needs to be emphasized again that when the preHandle() method of a certain interceptor returns true and is executed, it will put the afterCompletion() method of the interceptor into a special method stack.

       Registration and execution of multiple interceptors:

        Output result:

The execution sequence of methods and processor methods in multiple interceptors is as follows:

 

Guess you like

Origin blog.csdn.net/weixin_43725517/article/details/108269886