SpringBoot中如何放入静态资源及自定义静态资源的位置呢?
下文笔者讲述SpringBoot中放入静态资源及自定义静态资源位置的方法分享,如下所示
SpringBoot放入静态资源的方法
SpringBoot中默认放入静态资源的位置:
classpath:/static
classpath:/public
classpath:/resources
classpath:/META-INF/resources
classpath:指WEB-INF下面的classes目录
在Spring的代码中的位置为:src/main/resources目录。
即:
resources目录下默认有三个目录
static,public,resources中的内容,即可直接访问
SpringBoot指定静态资源所处位置的方法
方式1:使用配置文件配置静态资源的位置
使用spring.resources.static-locations:
即可配置静态资源文件的路径
注意事项:
使用以上方式,将会覆盖原静态资源文件
此时我们配置时,需将原静态路径都配置上
如:
spring.web.resources.static-locations=classpath:/META-INF/resources/,
classpath:/resources/,classpath:/static/,
classpath:/public/,classpath:/webhtml/
webhtml 是新的静态文件目录
方式2:使用程序配置静态资源的位置
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if(!registry.hasMappingForPattern("/static/**")){
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/webhtml/");
}
super.addResourceHandlers(registry);
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


