Spring Boot 拦截器

@Component
public class TestInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        System.out.println("TestInterceptor-----------------preHandle");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("TestInterceptor-----------------postHandle");
    }
}
@Component
public class JavasmWebMvcConfiguration implements WebMvcConfigurer {

    @Resource
    TestInterceptor testInterceptor;
    @Resource
    LoginInterceptor loginInterceptor;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //当前的这个方法,是管理拦截器的
        //registry注册拦截器
        registry.addInterceptor(testInterceptor)
                .addPathPatterns("/game/**")
                .excludePathPatterns("/game/list");

        registry.addInterceptor(loginInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/login/**");
    }
}
  • 练习

希望拦截器,拦截请求,校验登录的用户

一部分接口,必须登录之后才能访问,也有一部分接口,不登录也可以访问

通过自定义注解,来灵活区分哪个接口需要拦截

  • 自定义注解

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    public @interface JavasmAuth {
    }
    @Component
    public class LoginInterceptor implements HandlerInterceptor {
    
        @Override
        public boolean preHandle(HttpServletRequest request,
                                 HttpServletResponse response,
                                 Object handler) throws Exception {
            //如果 被访问的方法,有自定义注解,就走下面的流程,没有,直接放过
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            //获取 method对象上面的JavasmAuth注解
            JavasmAuth annotation = method.getAnnotation(JavasmAuth.class);
            if (annotation == null){
                //说明 方法上面 没有加密注解,不需要加密
                return true;
            }
            //代码执行到这里,说明 annotation不是null,方法上面与加密注解
            HttpSession session = request.getSession();
            Object user = session.getAttribute("user");
            if (user!=null){
                return true;
            }
            throw new JavasmException(ExceptionEnum.NotLoginError);
        }
    }

    使用

     @JavasmAuth
        @GetMapping("/list")
        public R queryList() {
            return R.ok(gameService.queryAll());
        }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值