拦截器配置"/>
SpringBoot拦截器配置
写下这个的原因是在实践过程中遇到了一个坑,拦截器配置好之后无论如何不生效,后面发现是启动类里面没有加注解,配置扫描路径,用如下2个方式
@SpringBootApplication(scanBasePackages={"com.example"})
或者
@ComponentScan 的作用就是根据定义的扫描路径,把符合扫描规则的类装配到spring容器中
@ComponentScan(basePackages = {"com.example"})
步骤1:
编写一个拦截器,用@Component注解,作用是将类转化为Spring bean,能被Spring容器管理
/*** jwt拦截器对请求进行拦截,判断请求的方法和注解*/
@Slf4j
@Component
public class JwtInterceptor implements HandlerInterceptor{/*** 请求前* @param request current HTTP request* @param response current HTTP response* @param handler chosen handler to execute, for type and/or instance evaluation* @return 返回true就是通过验证,false未通过验证* @throws Exception*/@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {String token = request.getHeader("token");log.info("token is :"+token);// 如果不是映射到方法的,直接通过if (!(handler instanceof HandlerMethod)) {return true;}// 获取请求的方法HandlerMethod handlerMethod = (HandlerMethod) handler;Method method = handlerMethod.getMethod();if (method.isAnnotationPresent(PassToken.class)) {if (method.getAnnotation(PassToken.class).required()) {// 执行认证if (token == null) {log.error("token 不存在,请重新登录");throw new RuntimeException("token 不存在,请重新登录");}return false;}}return false;}}
步骤2:编写一个拦截器配置类,并用@configuration注解,代表此类是一个配置类
/*** 自定义拦截器配置类注入到sping容器中*/@Configuration
public class InterceptorConfig implements WebMvcConfigurer {@Beanpublic JwtInterceptor getJwtInterceptor(){return new JwtInterceptor();}@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");}@Overridepublic void addInterceptors(InterceptorRegistry registry) {//addPathPatterns拦截的路径String[] addPathPatterns = {"/**"};//excludePathPatterns排除的路径String[] excludePathPatterns = {"/user/login","/user/noLg","/user/error"};//拦截所有请求registry.addInterceptor(getJwtInterceptor()).addPathPatterns(addPathPatterns).excludePathPatterns(excludePathPatterns);}}
步骤3:检查启动类是否配置了扫描路径
然后启动项目,打断点就可以看到进入了preHandle方法,说明配置成功
更多推荐
SpringBoot拦截器配置
发布评论