码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2020-07-05 17:26:07      阅读:81      评论:0      收藏:0      [点我收藏+]

标签:contex   over   控制   用户   json   service   else   eth   编程思想   

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

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容器所以可以运行在多种环境

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新版本配置拦截器在项目中的使用

标签:contex   over   控制   用户   json   service   else   eth   编程思想   

原文地址:https://www.cnblogs.com/chenyanbin/p/13246572.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!