Springboot拦截器

1、自定义拦截器实现类

//1、实现HandlerInterceptor接口便成为一个拦截器
public class JwtIntercepterUtil implements HandlerInterceptor {
    //2、实现其中的方法:
    // preHandle:此方法为在访问者调用任意一个接口之前拦截进行验证,最常用
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //3、自定义校验逻辑:返回true为放行,返回false为禁止通行,可通过设置response自定义返回的具体信息
        //例如:
        //获取并校验token,若无未登录则禁止通行并返回信息
        try{

            String token = request.getHeader("Authorization");
            System.out.println(token);
            JwtUtil jwtUtil = new JwtUtil();
            jwtUtil.isLegitimate(token);
            System.out.println(token);
            if (jwtUtil.isExpired(token)){
                Map map = new HashMap();
                map.put("401","登录过期,请重新登录");
                response.setContentType("application/json;charset=UTF-8");
                String json = new ObjectMapper().writeValueAsString(map);
                response.getWriter().println(json);
                return false;
            }
            return true;
        }catch (Exception e){
            Map map = new HashMap();
            map.put("code","401");
            map.put("message","登录状态异常,请重新登录");
            response.setContentType("application/json;charset=UTF-8");
            String json = new ObjectMapper().writeValueAsString(map);
            response.getWriter().println(json);
            return false;
        }
    }
}

2、建立config进行配置

//1、@Configuration注解定义此类为配置类,实现WebMvcConfigurer接口
@Configuration
public class IntercepterConfig implements WebMvcConfigurer {
    //2、实现addInterceptors方法
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //new一个自己定义的拦截器添加进来
        registry.addInterceptor(new JwtIntercepterUtil())
                //设置所有路径都需拦截
                .addPathPatterns("/**")
                //设置个别不需要拦截,自动放行的访问路径
                .excludePathPatterns("/login/**")
                //下面附带放行swagger的访问路径
                .excludePathPatterns("/swagger-ui.html")
                .excludePathPatterns("/swagger-resources/**")
                .excludePathPatterns("/webjars/springfox-swagger-ui/**")
                .excludePathPatterns("/v2/api-docs");

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值