12 spring mvc interceptor

Interceptor Introduction

Spring Web MVC interceptors processor, similar to the filter Filter Servlet Development, processor for preprocessing and postprocessing.

Common scenarios

  • Logging: log requests information, information for monitoring, statistical information calculated PV (Page View), etc.

  • Permission checks: such as login detection, detection is logged into the processor detects if there is no direct return to the login page

  • Performance monitoring: Sometimes a certain period in somehow slow, the start time may be recorded prior to entering the processor via the interceptor, the recording time after the end of the processing, whereby the processing time of the request

  • General Behavior: Cookie read information and to give the user objects in the user request, so as to facilitate subsequent processes use, as well as Locale, Theme information extraction, etc., as long as a plurality of processors are required to achieve using interceptors

The first Spring MVC interceptors

Spring MVC interceptor needs to implement  HandlerInterceptor an interface, the interface defines three methods, respectively  preHandle(), postHandle() and  afterCompletion(), our process is to intercept the user's request by rewriting these three methods.

  • preHandle(HttpServletRequest request, HttpServletResponse response, Object handle): This method is invoked prior request processing. Spring MVC The Interceptor is a chain called, or that there may be multiple requests Interceptor in a while in one application. Each call will be followed by the implementation of Interceptor in accordance with its declaration order, and are the first to perform the Interceptor in the  preHandle method, it is possible to carry out some pre-initialization or make a request for the current pretreatment In this method, you can also some judgment in this method to determine whether the request should continue. The return value is a Boolean value of Boolean type, when it is returned  false , it indicates the end of the request, and the subsequent Interceptor Controller will no longer performed; when the return value  true , the next will continue to call the Interceptor  preHandle method, if Interceptor is already the last time, it will be called the current method of request of the Controller.

  • postHandle(HttpServletRequest request, HttpServletResponse response, Object handle, ModelAndView modelAndView): The  preHandle interpretation method we know of this method include the back to say to  afterCompletion all the Interceptor only method currently belongs  preHandle return value of the method  true when the order is called. postHandle Method, that is, after the method call to execute the Controller after the current request is processed, but it will  DispatcherServlet be called before the view is rendered return, so we can deal with after the Controller In this method,  ModelAndView the operation target. postHandle Method is called with the direction of  preHandle the opposite, that is to say, Interceptor is the first statement of the  postHandle method but executed after the meeting.

  • afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handle, Exception ex): Also the needs of the current corresponding Interceptor is  preHandle the return value of the method  true are performed when. Therefore, the method after the end of the entire request, that is  DispatcherServlet executed after rendering the corresponding view, the main role of this method is to work for resource cleanup.

 Create a login interceptor

Log in to intercept two judges

  1. When accessing the login interface in addition, to determine whether the login if not logged in, jump to the login
  2. When accessing the login interface to determine whether the landing, if you are logged in, jump to the home page

 

step:

  • After a successful login, the user information into session
  • Creating LoginInterceptor realize the function 1
  • Creating ToLoginInterceptor realize the function 2
  • Interceptor arranged in spring-mvc.xml

Code:

After a successful login

//把登录信息放入session
            req.getSession().setAttribute("user",user);

LoginInterceptor

package com.example.my.shop.web.Interceptor;

import com.example.my.shop.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * 登录拦截器
 *
 */
public class LoginInterceptor implements HandlerInterceptor{
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        User user =(User) httpServletRequest.getSession().getAttribute("user");
       //用户未登录,重定向到登录页
        if(user==null){
            httpServletResponse.sendRedirect("/login");
            return false;
        }
        //放行
        return true;

    }

    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}

ToLoginInterceptor

package com.example.my.shop.web.Interceptor;

import com.example.my.shop.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

public class ToLoginInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        return true;
    }

    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

        //如果请求来自登录页
        if(modelAndView.getViewName().endsWith("login")){
            User user=(User)httpServletRequest.getSession().getAttribute("user");
            if(user!=null){
                httpServletResponse.sendRedirect("/main");
            }
        }
    }

    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}

spring-mvc.xml

  <!-- 拦截器配置,拦截顺序:先执行后定义的,排在第一位的最后执行。对除了static和/login之外的请求进行拦截,如果未登录,跳转登陆界面-->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <mvc:exclude-mapping path="/static/**"/>
            <mvc:exclude-mapping path="/login"/>
            <bean class="com.example.my.shop.web.Interceptor.LoginInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>
    <!-- 拦截器配置 对所有请求进行拦截-->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <bean class="com.example.my.shop.web.Interceptor.ToLoginInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>

So far, the code: https://download.csdn.net/download/shmily_syw/11242393

Editor:

https://www.funtl.com/zh/spring-mvc/Spring-MVC-%E6%8B%A6%E6%88%AA%E5%99%A8%E7%9A%84%E4%BD%BF%E7%94%A8.html#%E7%AC%AC%E4%B8%80%E4%B8%AA-spring-mvc-%E6%8B%A6%E6%88%AA%E5%99%A8

Guess you like

Origin blog.csdn.net/shmily_syw/article/details/92070396