html静态资源访问不到,Spring Boot静态资源不能访问问题

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

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

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

👿

怎么解决呢?

继承WebMvcConfigurerAdapter,当然如果使用Java8+,那么WebMvcConfigurerAdapter这个类以及过时了,可以直接实现WebMvcConfigurer接口,然后重写addInterceptors来添加拦截器:

@Configuration

public class InterceptorConfig implements WebMvcConfigurer {

@Override

public void addInterceptors(InterceptorRegistry registry) {

registry.addInterceptor(new UserInterceptor()).addPathPatterns("/user/**");

WebMvcConfigurer.super.addInterceptors(registry);

}

}

继承WebMvcConfigurationSupport,然后重写addResourceHandlers方法:

@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);

}

}

除此之外,还有一个注解@EnableWebMvc,也会让自动配置失效,就这样。

😎

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值