SpringBoot2.X新版本配置拦截器在项目中的使用

拦截器:和过滤器用途基本类似

SpringBoot2.X新版本配置拦截器 implements WebMvcConfigure

  • 自定义拦截器 HandlerInterceptor
    • preHandle:调用Controller某个方法之前
    • postHandle:Controller之后调用,视图渲染之前,如果控制器Controller出现了异常,则不会执行此方法
    • afterCompletion:不管有没有异常,这个afterCompletion都会被调用,用于资源清理
  • 按照注册顺序进行拦截,先注册,先被拦截

拦截不生效常见问题

  1. 是否有加@Configuration
  2. 拦截路径是否有问题 **和*
  3. 拦截器最后路径一定要 /** 如果是目录的话则是 /*/

场景:权限控制、用户登陆状态控制等

和Filter过滤器的区别

Filter和Interceptor二者都是AOP编程思想的体现,功能基本都可以实现
拦截器功能更强大些,Filter能做的事情它都能做
Filter在只在Servlet前后起作用,而Interceptor能够深入到方法前后、异常抛出前后等
依赖于Servlet容器既web应用中,而Interceptor不依赖于Servlet容器所以可以运行在多种环境
在接口调用的生命周期,Interceptor可以被多次调用,而Filter只能在容器初始化时调用一次。
Filter和Interceptor的执行顺序
过滤前->拦截前->action执行->拦截后->过滤后

CustomWebMvcConfigure.java

package net.cyb.demo.interceptor;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 拦截器配置类
 */
@Configuration
public class CustomWebMvcConfigure implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getLoginInterceptor()).addPathPatterns("/api/v1/pri/**");
        WebMvcConfigurer.super.addInterceptors(registry);
    }
    @Bean
    public LoginIntercepter getLoginInterceptor(){
        return new LoginIntercepter();
    }
}

LoginIntercepter.java

package net.cyb.demo.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import net.cyb.demo.domain.User;
import net.cyb.demo.service.impl.UserServiceImpl;
import net.cyb.demo.utils.JsonData;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class LoginIntercepter implements HandlerInterceptor {
    private static final ObjectMapper objectMapper=new ObjectMapper();
    private void renderJson(HttpServletResponse response,String json){
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        try{
            PrintWriter writer=response.getWriter();
            writer.print(json);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        System.out.println("LoginIntercepter preHandle==========");
        String token = req.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            token = req.getParameter("token");
        }
        if (StringUtils.isEmpty(token)) {
            JsonData jsonData=JsonData.buildError(-3,"未登陆");
            String jsonStr=objectMapper.writeValueAsString(jsonData);
            renderJson(resp, jsonStr);
            return false;
        } else {
            //判断token是否合法 TODO
            User user = UserServiceImpl.sessionMap.get(token);
            if (user != null) {
                return true;
            }else {
                JsonData jsonData=JsonData.buildError(-2,"登陆失败,token无效");
                String jsonStr=objectMapper.writeValueAsString(jsonData);
                renderJson(resp, jsonStr);
                return false;
            }
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("LoginIntercepter postHandle==========");
        HandlerInterceptor.super.postHandle(request,response,handler,modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("LoginIntercepter afterCompletion==========");
        HandlerInterceptor.super.afterCompletion(request,response,handler,ex);
    }
}

 

你可能感兴趣的:(SpringBoot2.X新版本配置拦截器在项目中的使用)