SpringMVC响应请求
# SpringMVC响应请求
| 实验 | 内容 | 目标 |
|---|---|---|
| 实验1 | 返回JSON数据 | 测试对象json写出 |
| 实验2 | 返回ResponseEntity | 测试文件下载 |
| 实验3 | 引入thymeleaf模板引擎 | 测试服务端渲染 |
# 文件下载
/**
* 文件下载
* HttpEntity:拿到整个请求数据
* ResponseEntity:拿到整个响应数据(响应头、响应体、状态码)
*/
@RequestMapping("/download")
public ResponseEntity<InputStreamResource> download() throws IOException {
//以下代码无需修改
FileInputStream inputStream = new FileInputStream("C:\\Pictures\\1.jpg");
//一口气读会溢出
// byte[] bytes = inputStream.readAllBytes();
//1、文件名中文会乱码:解决:
String encode = URLEncoder.encode("哈哈美女.jpg", "UTF-8");
//2、文件太大会oom(内存溢出)
InputStreamResource resource = new InputStreamResource(inputStream);
return ResponseEntity.ok()
//内容类型:流
.contentType(MediaType.APPLICATION_OCTET_STREAM)
//内容大小
.contentLength(inputStream.available())
// Content-Disposition :内容处理方式
.header("Content-Disposition", "attachment;filename="+encode)
.body(resource);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# Thymeleaf模板引擎
SpringBoot整合的SpringMVC默认不支持JSP
- 引入 thymeleaf 作为模型引擎,渲染页面
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
1
2
3
4
2
3
4
- 默认规则
- 页面:src/main/resources/templates
- 静态资源:src/main/resources/static
Last Updated: 2025/12/02, 11:22:00