Spring Boot static静态资源不能访问问题

8 篇文章 0 订阅
5 篇文章 0 订阅

之前做了一个demo,当时并没有注意,后来发现静态资源不能访问了。

    Spring Boot自动配置了classpath:/static/下面的资源为静态资源,后来网上找了很多的方法都试过了,解决不了。

    于是我重新写了一个项目,把这个旧项目的配置一个一个的移动过去,最后发现是我配置的拦截器的问题。因为我配置拦截器继承的类是:WebMvcConfigurationSupport这个类,它会让spring boot的自动配置失效。

    怎么解决呢?

    第一种可以继承WebMvcConfigurerAdapter,当然如果是1.8+WebMvcConfigurerAdapter这个类以及过时了,可以直接实现WebMvcConfigurer接口,然后重写addInterceptors来添加拦截器:

1
2
3
4
5
6
7
8
9
10
@Configuration
public  class  InterceptorConfig  implements  WebMvcConfigurer {
 
     @Override
     public  void  addInterceptors(InterceptorRegistry registry) {
         registry.addInterceptor( new  UserInterceptor()).addPathPatterns( "/user/**" );
         WebMvcConfigurer. super .addInterceptors(registry);
     }
 
}

    或者还是继承WebMvcConfigurationSupport,然后重写addResourceHandlers方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Configuration
public  class  InterceptorConfig  extends  WebMvcConfigurationSupport {
 
     @Override
     protected  void  addInterceptors(InterceptorRegistry registry) {
         registry.addInterceptor( new  UserInterceptor()).addPathPatterns( "/user/**" );
         super .addInterceptors(registry);
     }
     
     @Override
     protected  void  addResourceHandlers(ResourceHandlerRegistry registry) {
         registry.addResourceHandler( "/**" ).addResourceLocations( "classpath:/static/" );
         super .addResourceHandlers(registry);
     }
     
}

转自:https://www.acgist.com/article/488.html

评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值