在Spring MVC中,对于静态资源的访问需要开发者手动去配置。Spring Boot对此进行了简化,提供了自动化配置。
Spring Boot默认会过滤所有的静态资源,静态资源的位置一共有五个。
图中标出了四个,还有一个是根目录,即/
,图中序号按照优先级。
上面是Spring Boot默认的静态资源策略,如果不能满足你,可以使用自定义策略。
自定义策略有两种方式来配置,一种是我们之前说过的Properties配置(application.properties)。例如:
spring.mvc.static-path-pattern=/static/**
spring.resources.static-locations=classpath:/static/
上述配置了过滤规则和静态资源位置。
重启项目,访问http://localhost:8080/static/xxx.png
,你就能访问到你想看到的资源。
另一种方式是Java编码方式:
package xyz.fengqing11.hellospringboot;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MywebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/static/**")
.addResourceLocations("classpath:/static/");
}
}
重启项目,效果和上面的一样。
-end-