您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# SpringBoot中怎么获取静态资源路径
## 一、静态资源默认路径
在SpringBoot中,静态资源默认存放在以下位置(优先级从高到低):
1. `classpath:/META-INF/resources/`
2. `classpath:/resources/`
3. `classpath:/static/`
4. `classpath:/public/`
当浏览器发起静态资源请求时,SpringBoot会按此顺序查找资源文件。
## 二、自定义静态资源路径
### 1. 通过配置文件修改
在`application.properties`或`application.yml`中配置:
```properties
# 单个路径
spring.web.resources.static-locations=classpath:/custom-static/
# 多个路径(用逗号分隔)
spring.web.resources.static-locations=classpath:/custom-static/,file:/opt/static/
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/custom-static/", "file:/opt/static/");
}
}
@Autowired
private ResourceLoader resourceLoader;
public void getResourcePath() throws IOException {
Resource resource = resourceLoader.getResource("classpath:static/example.txt");
File file = resource.getFile();
String absolutePath = file.getAbsolutePath();
}
@Autowired
private ServletContext servletContext;
public void getRealPath() {
String realPath = servletContext.getRealPath("/static/example.txt");
}
@Autowired
private Environment env;
public void getConfiguredPath() {
String staticLocations = env.getProperty("spring.web.resources.static-locations");
}
@Autowired
private ResourceHttpRequestHandler resourceHandler;
public void getResourceUrl() {
// 需要通过请求上下文获取
}
@RequestMapping("/getUrl")
public String getResourceUrl(HttpServletRequest request) {
return ServletUriComponentsBuilder.fromRequest(request)
.replacePath("/static/example.jpg")
.toUriString();
}
getRealPath()
返回null,建议使用Resource.getInputStream()
file:
前缀指定绝对路径spring.web.resources.cache.period=3600
spring.web.resources.cache.cachecontrol.max-age=1h
掌握SpringBoot静态资源路径的获取和管理技巧,能够帮助开发者更灵活地处理各种资源加载需求。根据实际场景选择合适的方法,可以显著提升应用的稳定性和可维护性。 “`
注:实际字数为约650字,如需扩展到850字,可以: 1. 增加更多代码示例 2. 添加异常处理场景 3. 补充性能优化建议 4. 增加不同场景下的解决方案对比 5. 添加SpringBoot版本差异说明
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。