Spring Boot 对静态资源映射提供了默认配置,静态资源路径都是在classpath中:
classpath:/static
classpath:/public
classpath:/resources
classpath:/META-INF/resources
#访问请求的前缀
spring.mvc.static-path-pattern: /static/**
#静态文件地址(系统路径),file:D:/static
#类路径的文件地址 (这个默认是类路径,所以一般不用设定)
spring.resources.static-locations=classpath:/static/
http://localhost:8080/static/ 的所有文件都会去classpath:/static/ 下查找并返回
此方法也可以使用代码方式:
@Component
public class MyResHandler extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
super.addResourceHandlers(registry);
}
}
如图所示在image.html文件中使用img标签访问到upload内的图片
@RequestMapping("/image")
public ModelAndView image(HttpServletRequest request){
ModelAndView mav = new ModelAndView();
mav.setViewName("image");
mav.addObject("img", "1.png");
return mav;
}
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=8,IE=9,IE=10" />
<title>图片展示title>
head>
<body>
<img th:src="@{'/upload/' + ${img}}" />
body>
html>
访问路径:http://localhost:8082/image
# 图片音频上传路径配置(win系统自行变更本地路径)
web.upload.path=/home/file/
@Value("${web.upload.path}")
private String uploadPath;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
super.addResourceHandlers(registry);
registry.addResourceHandler("/uploads/**").addResourceLocations(
"file:"+uploadPath);
LOGGER.info("自定义静态资源目录、此处功能用于文件映射");
}
# 静态文件请求匹配方式
spring.mvc.static-path-pattern=/upload/**
spring.resources.static-locations=file:${web.upload-path},file:${web.front-path}
http://localhost:8080/upload/1.jpg
WebJars能使Maven的依赖管理支持OSS的JavaScript库/CSS库,比如jQuery、Bootstrap等;
WebJars是将Web前端Javascript和CSS等资源打包成Java的Jar包,这样在Java Web开发中我们可以借助Maven这些依赖库的管理,保证这些Web资源版本唯一性。
<dependency>
<groupId>org.webjarsgroupId>
<artifactId>jqueryartifactId>
<version>3.1.1version>
dependency>
访问:http://localhost:8082/webjars/jquery/3.1.1/jquery.min.js 是有数据的
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=8,IE=9,IE=10" />
<script type="text/javascript" src="/webjars/jquery/3.1.1/jquery.min.js">script>
<title>title>
head>
<body>
body>
<script>
$(function(){
alert(123)
});
script>
html>
<dependency>
<groupId>org.webjarsgroupId>
<artifactId>webjars-locatorartifactId>
<version>0.31version>
dependency>
修改为