spring 拦截器

1.拦截器定义

这里定义一个jwt拦截器,继承HandlerInterceptor 重写里面的方法实现拦截

@Component
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {

    /**
     * 操作之前拦截
     * @param request
     * @param response
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
       log.info("经过拦截器");
       String token = request.getHeader("Authorization");
       if (StringUtils.isEmpty(token)){
           throw new Exception("权限不足");
       }
       if (StringUtils.isNotEmpty(token)){
           //对令牌进行验证
           try {
               //解析令牌
               Claims claims = JJwtUtiles.parseToken(token);
           }catch (Exception e){
               throw new Exception("令牌有误");
           }
       }
        return true;
    }

    /**
     * 操作之后拦截
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 最终释放资源
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param e
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

2.注册拦截器

@Configuration表明为一个配置类,继承WebMvcConfigurationSupport 注册拦截器

@Configuration
public class InterceptorConfig extends WebMvcConfigurationSupport {

    @Autowired
    private JwtInterceptor jwtInterceptor;
    /**
     * 注册拦截器
     * @param registry
     */
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        //声明拦截对象 和请求    (拦截所有请求 除登录外)
        registry.addInterceptor(jwtInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/**/login/**");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值