SpringBoot拦截器配置

编程入门 行业动态 更新时间:2024-10-25 13:15:36

SpringBoot<a href=https://www.elefans.com/category/jswz/34/1771281.html style=拦截器配置"/>

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拦截器配置

本文发布于:2023-12-08 03:48:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1672269.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:拦截器   SpringBoot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!