叙述
当我们使用 IntelliJ IDEA 创建 Spring Boot 项目,会默认创建 classpath:/static/ 目录,我们直接把静态资源放在这个目录下即可。
我们直接在浏览器中输入“http://localhost:8080/java.png”即可看到我们添加的这张图片。
自定义策略
如果默认的静态资源过滤策略不能满足开发需求,也可以自定义静态资源过滤策略,自定义的方式有如下两种。
通过配置:
我们在 application.properties 中直接定义过滤规则和静态资源位置
- 过滤规则改为 /static
- 静态资源位置仍然是 classpath:/static/ 没有变化
spring.mvc.static-path-pattern=/static/**
spring.resources.static-locations=classpath:/static/
重启项目,我们这次可以在浏览器中输入“http://localhost:8080/static/java.png”来访问添加的静态图片。
Java编码:
package com.example.demo;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 静态资源映射
*/
@Component
public class MyWebMvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**")
.addResourceLocations("classpath:/static/");
}
}
重启项目,效果同上面是一样的。我们同样可以在浏览器中输入“http://localhost:8080/static/java.png”来访问添加的静态图片。