持续学习&持续更新中…
守破离
【Java从零到架构师第③季】【44】SpringBoot-SpringMVC
SpringMVC的配置1
SpringMVC的配置2
org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties
spring:
mvc:
servlet:
load-on-startup: 0
format:
# 默认
# date: dd/MM/yyyy
date: yyyy-MM-dd
date-time: yyyy-MM-dd HH:mm:ss
文件上传
spring:
servlet:
multipart:
max-file-size: 10MB
max-request-size: 100MB
SpringBoot项目的文件保存路径需要自己手动指定,但是我们肯定不能将路径硬编码到代码中,可以使用application.yml:
project:
uploads:
base-path: D:/uploads/
image-path: image/
video-path: video/
others-path: others/
@Component
@Data
@AllArgsConstructor
@NoArgsConstructor
@ConfigurationProperties("project")
public class ProjectProperties {
private Uploads uploads;
@Data
@AllArgsConstructor
@NoArgsConstructor
public static class Uploads {
private String basePath;
private String imagePath;
private String videoPath;
private String othersPath;
}
}
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
@RestController
@RequestMapping("/test")
public class TestController {
@Autowired
private ProjectProperties projectProperties;
@PostMapping("/fileUpload")
public String fileUpload(MultipartFile file) throws Exception {
final ProjectProperties.Uploads uploads = projectProperties.getUploads();
final String basePath = uploads.getBasePath();
final String imagePath = uploads.getImagePath();
final String fileName = file.getOriginalFilename();
// final String fileName = UUID.randomUUID() + "." + FilenameUtils.getExtension(file.getOriginalFilename());
File destFile = new File(basePath + imagePath + fileName);
// 确保目标文件所在的目录存在
// destFile.getParentFile().mkdirs();
FileUtils.forceMkdirParent(destFile);
file.transferTo(destFile);
return "success";
}
}
静态资源访问
静态资源访问—映射
静态资源访问—映射本质
@Configuration
public class SpringMVCConfiguration implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/static/")
.addResourceLocations("file:///D:/uploads/");
}
}
相比于application.yml还可以灵活的这样写:
@Configuration
public class SpringMVCConfiguration implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/static/");
registry.addResourceHandler("/uploads/**")
.addResourceLocations("file:///D:/uploads/");
}
}
静态资源访问—映射webjars
前端的很多东西就是静态资源,比如jQuery的js文件、…,我们可以直接在项目中引用它们,这个时候就可以使用webjars技术了。
官网:https://www.webjars.org/
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.5.1</version>
</dependency>
<button type="button" id="btn-add">添加</button>
<!--<script th:src="@{/webjars/jquery/3.5.1/jquery.js}"></script>-->
<script th:src="@{/webjars/jquery/3.5.1/jquery.min.js}"></script>
<script>
$('#btn-add').click(() => {
alert('点击了添加')
})
</script>
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter源码:
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
return;
}
addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");
addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
registration.addResourceLocations(this.resourceProperties.getStaticLocations());
if (this.servletContext != null) {
ServletContextResource resource = new ServletContextResource(this.servletContext, SERVLET_LOCATION);
registration.addResourceLocations(resource);
}
});
}
文件下载
<a th:href="@{/test.txt}">访问test.txt文件</a>
<a th:href="@{/download}">以附件的形式下载test.txt文件</a>
@GetMapping("/download")
public void download(HttpServletResponse response) throws Exception {
// 把文件以附件的形式返回
// 设置响应头
response.setHeader("Content-Disposition", "attachment; filename=test.txt");
// 读取文件
try (InputStream is = new ClassPathResource("static/test.txt").getInputStream()) {
// 将文件数据利用response写回到客户端
IOUtils.copy(is, response.getOutputStream());
}
}
参考
小码哥-李明杰: Java从0到架构师③进阶互联网架构师.
本文完,感谢您的关注支持!