SpringBoot第二章拦截器

1、创建拦截器,返回true表示通过,返回false表示失败,用于身份认证、权限登录、注解判断等

public class MyInterceptor  implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
         System.out.println("进去方法之前,判断是否满足注解");
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("进入方法之后,返回值");
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }
}

2、配置注册拦截器,一定要写@Configuration,否则无法自动注册

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

@Override
public void addInterceptors(InterceptorRegistry registry) {
//注册TestInterceptor拦截器
InterceptorRegistration registration = registry.addInterceptor(new MyInterceptor());
registration.addPathPatterns("/**"); //所有路径都被拦截
registration.excludePathPatterns( //添加不拦截路径
"你的登陆路径", //登录
"/**/*.html", //html静态资源
"/**/*.js", //js静态资源
"/**/*.css", //css静态资源
"/**/*.woff",
"/**/*.ttf"
);
}
}
原文地址:https://www.cnblogs.com/topguntopgun/p/15471155.html