public class InterceptorConfig extends WebMvcConfigurationSupport
时间: 2023-07-20 20:21:13 浏览: 57
这段代码是在Java中配置拦截器的方式之一。它创建了一个名为InterceptorConfig的类,并继承了WebMvcConfigurationSupport类。WebMvcConfigurationSupport是SpringMVC提供的一个类,它支持自定义配置SpringMVC的一些特性。InterceptorConfig类中可以重写父类的方法,来自定义拦截器的配置。
在这个类中,我们可以通过重写addInterceptors方法,来添加我们自定义的拦截器。该方法会在SpringMVC启动时被调用,我们可以在其中添加我们需要的拦截器,来对请求进行拦截和处理。
需要注意的是,这种方式配置拦截器会覆盖SpringBoot默认的拦截器配置,因此需要手动添加一些默认配置,比如静态资源的访问等。同时,该方式也存在一些局限性,比如在使用@EnableWebMvc注解开启SpringMVC的情况下,就不能使用该方式了。
相关问题
解释public class InterceptorConfig extends WebMvcConfigurationSupport{ @Bean public AuthorizationInterceptor getAuthorizationInterceptor() { return new AuthorizationInterceptor(); } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(getAuthorizationInterceptor()).addPathPatterns("/**").excludePathPatterns("/static/**"); super.addInterceptors(registry); } /** * springboot 2.0配置WebMvcConfigurationSupport之后,会导致默认配置被覆盖,要访问静态资源需要重写addResourceHandlers方法 */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/**") .addResourceLocations("classpath:/resources/") .addResourceLocations("classpath:/static/") .addResourceLocations("classpath:/admin/") .addResourceLocations("classpath:/front/") .addResourceLocations("classpath:/public/"); super.addResourceHandlers(registry); } }
这段代码是一个拦截器配置类,它继承了WebMvcConfigurationSupport类,并且重写了addInterceptors和addResourceHandlers方法。
其中,getAuthorizationInterceptor()方法返回一个AuthorizationInterceptor对象,它是一个自定义的拦截器。
addInterceptors方法用于配置拦截器,这里将getAuthorizationInterceptor()加入到了拦截器链中,并指定了拦截的路径为"/**",但是排除了静态资源的路径"/static/**"。
addResourceHandlers方法则是用于配置静态资源的位置,这里将"/resources/"、"/static/"、"/admin/"、"/front/"和"/public/"这些路径都映射到"/**"路径下,这样就可以通过访问这些路径下的静态资源了。
@Configuration public class InterceptorConfig extends WebMvcConfigurationSupport { @Override protected void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/swagger-ui/**") .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/"); super.addResourceHandlers(registry); } @Override protected void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(jwtInterceptor()) .addPathPatterns("/**") .excludePathPatterns("/user/login", "/user/register", "/**/export", "/**/import", "/file/**") .excludePathPatterns("/swagger**/**", "/webjars/**", "/v3/**", "/doc.html"); super.addInterceptors(registry); } @Bean public JwtInterceptor jwtInterceptor() { return new JwtInterceptor(); } }
这是一个Java Spring Boot项目的拦截器配置类。在这个类中,我们首先重写了`addResourceHandlers()`方法来添加静态资源的处理器,这里是Swagger UI的资源,以便我们可以访问Swagger UI页面。
然后,我们重写`addInterceptors()`方法,并添加了一个自定义的JwtInterceptor拦截器。该拦截器将会拦截所有的请求(除了一些特定的排除路径),并检查请求头中是否包含了JWT Token,如果没有,则拒绝请求。这种方式可以保证只有经过认证的用户才能够访问我们的API接口。
最后,我们通过使用`@Bean`注解将JwtInterceptor类实例化为一个Bean。这样,我们就可以在其他地方通过依赖注入的方式来使用该拦截器了。