SpringBoot拦截器的使用

总结一下SpringBoot下拦截器的使用,步骤很简单:ide

1.自定义本身的拦截类,拦截类须要继承HandlerInterceptor接口并实现这个接口的方法。post

 @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        //方法调用前执行
        return true;//返回为false,拦截器拦截的方法不会调用
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    //方法执行结束后执行
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    
    //该方法将在整个请求完成以后,也就是DispatcherServlet渲染了视图执行, 这个方法的主要做用是用于清理资源的,
    }    

2.配置类须要继承WebMvcConfigurerAdapter类spa

  @Autowired
    private LoginInterceptor loginInterceptor;//本身定义的拦截器类

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(loginInterceptor).addPathPatterns("拦截URL,能够不填默认所有请求拦截");
    }

3.启动SpringBoot应用便可。code

相关文章
相关标签/搜索