springboot拦截器Interceptor

1、创建一个拦截器类并实现HandlerInterceptor接口,重写preHandle、postHandle、afterCompletion这3个方法

@Slf4j
@Component
public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//Controller方法处理之前,若返回false,则中断执行,注意:不会进入afterCompletion
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView
            modelAndView) throws Exception {
//preHandle返回true,Controller方法处理完之后,DispatcherServlet进行视图的渲染之前,也就是说在这个方法中你可以对ModelAndView进行操作

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception
            ex) throws Exception {
//preHandle返回true,DispatcherServlet进行视图的渲染之后,多用于清理资源
    }

}

2、创建拦截器的配置类,定义拦截规则

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        String[] addPath = {"/", "/platform", "/api/platform/**"};//拦截的路径
        String[] excludePath = {"/api/platform/testdata/getAtRt"};//排除的路径
        registry.addInterceptor(new UserInterceptor()).addPathPatterns(addPath).excludePathPatterns(excludePath);
    }
}

//addPathPatterns("/") 表示拦截根目录请求,直接请求域名后面没有加具体路径
//addPathPatterns("/**") 表示拦截所有的请求,
//addPathPatterns("/test/**") 表示拦截/test/ 下的所有路径请求,
//addPathPatterns("/test/*") 表示拦截/test/abc,拦截/test/aaa , 不拦截 /test/abc/def
//addPathPatterns("/test/**").excludePathPatterns("/test/login", “/test/register”) 表示拦截/test/ 下的所有路径请求,但不拦截 /test/login 和 /test/register

springboot拦截器Interceptor_第1张图片

 

你可能感兴趣的:(SpringBoot,spring,boot,spring,java)