SpringBoot 拦截器Interceptor

1. 编写自定义拦截器

  • 编写自定义拦截器
  • 实现HandlerInterceptor接口
  • 重写接口方法preHandle、postHandle、afterCompletion

如:

public class CustomInterceptor  implements HandlerInterceptor {

    private static final ObjectMapper mapper = new ObjectMapper();

    public CustomInterceptor() {
        System.out.println("init CustomInterceptor....");
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // get token
        String token = request.getHeader("token");
        if(!StringUtils.hasLength(token)){
            token = request.getParameter("token");
        }
        if (!StringUtils.hasLength(token)){
            renderResponse(response, "token not input");
        }
        // verify token
        User user = Cache.userCache.get(token);
        if(user != null){
            //token is ok
            return true;
        }else {
            //token verify failure
            //write response
            //write response
            renderResponse(response, "token verify failure");
            return false;
        }
    }

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

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

    private void renderResponse(HttpServletResponse response, String json){
        response.setCharacterEncoding("utf8");
        response.setContentType("application/json");
        try (PrintWriter writer = response.getWriter()) {
            writer.write(mapper.writeValueAsString(JsonData.buildError(json)));
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}

2. 注册拦截器

  • 自定义配置类
  • 配置类实现WebMvcConfigurer接口
  • 重写接口方法addInterceptors
  • 在addInterceptors方法中注册自定义拦截器
  • 在配置类上加@Configuration注解

如:

@Configuration
public class CustomWebMvcConfigurer implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //拦截器最后路径一定要 /**  如果是目录的话则是 /*/
        registry.addInterceptor(getCustomInterceptor()).addPathPatterns("/api/v1/pri/**");
        //register 
        WebMvcConfigurer.super.addInterceptors(registry);
    }

    /**
     * put CustomInterceptor into ioc
     * @return
     */
    @Bean
    public CustomInterceptor getCustomInterceptor(){
        return new CustomInterceptor();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值