SpringBoot:自定义拦截器

一:理论实现

  • 实现接口-HandlerInterceptor,重写其中的三个方法
  • 实现接口WebMvcConfigurer,重写addInterceptors方法,注册拦截器

二:实战

  • 书写我自己的拦截器
@Component
public class MyInterceptor implements HandlerInterceptor {
    //请求处理前,也就是访问Controller前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String num = request.getParameter("num");
        if(num==null){
            System.out.println("被拦截器拦截了");
            return false;
        }else {
            return true;
        }
    }
    //请求已经被处理,但在视图渲染前
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("请求处理结束了");
    }
    //请求结果结果已经渲染好了,response没有进行返回但也无法修改reponse了(一般用于清理数据)
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
  • 书写配置类
@Configuration
public class MyConfig implements WebMvcConfigurer {
    @Autowired
    private MyInterceptor myInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 通过registry来注册拦截器,通过addPathPatterns来添加拦截路径
        registry.addInterceptor(this.myInterceptor).addPathPatterns("/**");
    }
}
  • 编写controller进行测试
@RestController
public class TestController {
    @GetMapping("hi")
    public String testController(){
        System.out.println("我正在处理请求");
        return "这是一个拦截器测试类";
    }
}

你可能感兴趣的:(Spring,Boot)