【SpringMVC】| SpringMVC Interceptor

Table of contents

One: SpringMVC interceptor

1. Introduction to interceptors

2. HandlerInterceptor interface analysis

3. Custom interceptors implement permission verification


One: SpringMVC interceptor

The Interceptor interceptor in SpringMVC is mainly used to intercept specified user requests and perform corresponding preprocessing and postprocessing. The time point of its interception is "the processor mapper maps the processor class to be executed according to the request submitted by the user, and also finds the processor adapter to execute the processor class, before the processor adapter executes the processor" . Of course, when the processor mapper maps the processor class to be executed, the interceptor and the processor have been combined into a processor execution chain and returned to the central scheduler.

1. Introduction to interceptors

(1) Application scenarios of interceptors 

Additional processing for requests and responses, adding pre-processing, post-processing and final processing in the process of request and response ; mainly used in the following scenarios:

① Logging: Logs that record request information.

②Privilege check: such as login check.

③ Performance testing: the execution time of the testing method.

(2) The execution principle of the interceptor

①preHandle(): Operate before the request is processed; preprocessing .
②postHandle(): After the request is processed, but before the result is rendered, the operation can change the response result; post-processing.
③afterCompletion: After all requests and responses are completed, perform aftermath work, clean up objects, and close resources; final processing.

(3) Two ways of interceptor implementation

① Inherit the parent class of HandlerInterceptorAdapter [Handler Intercept Adapter] .
Implement the HandlerInterceptor [Handler Interceptor] interface . It is recommended to use the interface implementation method, because inheritance is single inheritance.

2. HandlerInterceptor interface analysis

A custom interceptor needs to implement the HandlerInterceptor interface; and the interface contains three methods:

(1)preHandle

This method is executed before the handler method is executed . Its return value is boolean type . If it is true , the processor method will be executed immediately , and the afterCompletion() method will be put into a special method stack for execution.

(2)postHandle

This method is executed after the handler method is executed . If the handler method is not executed in the end, the method will not be executed . Since this method is executed after the processor method is executed, and the method parameters include ModelAndView, this method can modify the processing result data of the processor method, and can modify the jump direction.

(3)afterCompletion

When the preHandle() method returns true , the method will be placed in a special method stack, and the method will not be executed until all the work in response to the request is completed. That is, this method is executed after the central scheduler renders (data fills) the response page. At this time, the operation of ModelAndView will not help the response. afterCompletion is the last executed method to clear resources, such as adding data to the Controller method.

3. Custom interceptors implement permission verification

(1) Transform the login method and store user information in the session for authority verification

Details: We must pay attention to whether our login interface login.jsp jumps to /login or /login.action; whether there is an action or not directly determines whether the path of the interceptor exclude-mapping passes with or without .action!

package com.bjpowernode.controller;

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

import javax.servlet.http.HttpServletRequest;

@Controller
public class WebInfAction {
    // 首先要跳转到登录页面
    @RequestMapping("/showLogin")
    public String submit(){
        System.out.println("访问login.jsp进行登录");
        return "login";
    }
    // 跳转到login.jsp后,在进行判断
    @RequestMapping("/login")
    public String login(String name, String pwd, HttpServletRequest request){ // 与前端保持一致,提交的数据自动吸过来
        if ("root".equalsIgnoreCase(name) && "123".equalsIgnoreCase(pwd)){
            // 在session中存储用户信息(把name存进去),用于权限验证
            request.getSession().setAttribute("user",name);

            return "main";
        }else {
            request.setAttribute("msg","用户名或者密码不正确");
            return "login";
        }
    }
}

(2) Develop the function of the interceptor, implement the HandlerInterceptor interface, and rewrite the preHandle() method

package com.bjpowernode.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;

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

public class LoginInterceptor implements HandlerInterceptor {
    // 重写preHandle方法
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 是否登录的判断
        if(request.getSession().getAttribute("user") == null){ // 能取出来,表示登录过
            // 没有登录,打回到登录的页面,并给出提示
            request.setAttribute("msg","请先去登录!");
            request.getRequestDispatcher("WEB-INF/jsp/login.jsp").forward(request,response);
            return false;
        }
        // 如果登录过,就放行往下走
        return true;
    }
}

(3) Register the interceptor in the springmvc.xml file

An interceptor chain can be configured in the interceptor, which is checked layer by layer; here we only need to configure one, and configure three parts in total:

① Map the requests to be intercepted, generally set to all intercepted.

② Then set the request to be released.

③Configure the class that implements the function of the specific interceptor.

    <!--注册拦截器-->
    <mvc:interceptors>
        <mvc:interceptor>
            <!--映射要拦截的请求-->
            <mvc:mapping path="/**"/>
            <!--配置要放行的请求-->
            <mvc:exclude-mapping path="/showLogin"/><!--登录的页面-->
            <mvc:exclude-mapping path="/login"/><!--登录验证的页面-->
            <!--配置具体的拦截器实现功能的类-->
            <bean class="com.bjpowernode.interceptor.LoginInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>

(4) Test:

Before logging in, we still know showMain or showIndex. Direct access is inaccessible and blocked.

After successfully logging in, we do not close the current session, but reopen a window, and we can access it directly

Guess you like

Origin blog.csdn.net/m0_61933976/article/details/128847189