Fork me on GitHub

SpringMVC学习7-响应和下载

Spring MVC

SpringMVC是基于MVC思想的JAVA WEB实现框架,是Spring家族的一员,它基于前置控制器来接收并分发请求,支持参考验证、请求参数封装、拦截、Restful等功能,是目前较为流行的MVC框架

本系列学习笔记包含如下的课程内容:

  • MVC思想
  • Hello案例
  • 请求和响应处理
  • 文件上传和下载处理
  • 参数验证
  • 请求拦截
  • RESTful风格
  • 日志

Response

Spring MVC 在提供 Html,JSP 等常规视图的同时, 也支持返回多种常见响应格式。

XML 格式响应

  • 通过 produces = "text/xml" 来设置响应内容为 XML
  • @ResponseBody 将返回数据作为响应主体
1
2
3
4
5
6
7
8
@RequestMapping(value = "/user.xml", method = RequestMethod.GET, produces = "text/xml")
@ResponseBody
public User getXmlUser() {
User user = new User();
user.setName("jack");
user.setPassword("123");
return user;
}

切记,要使用 @XmlRootElement 来对 User 进行注解,否则将会报 Http Status 406 错误:
The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request “accept” headers.

比如:

1
2
3
4
5
6
7
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class User {

private String name;
private int age;

总之,在控制器的方法的返回类型所对应类名上面, 一定要加 @XmlRootElement

用例分析:

如果你的项目中,需要返回 XML 的数据格式,并且数据是动态的(比如,来自数据库),则可以考虑以上的实现.

JSON 格式响应

返回json格式的字符串

配置依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.6.0</version>
</dependency>
  • 通过 produces = "application/json" 来设置响应内容为 JSON
  • @ResponseBody 将返回数据作为响应主体
1
2
3
4
5
6
7
8
@RequestMapping(value = "/demo2", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public User getJsonUser() {
User user = new User();
user.setName("mike");
user.setPassword("456");
return user;
}

注:这种方式对实体类User没有要求要打上@RootElement注解.

File下载

思路和基于 Servlet 的实现一致,都是设置响应内容为具体文件类型再将文件写入输出流即可。

代码片断:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@RequestMapping(value = "/demo3", method = RequestMethod.GET)
public void getFile(HttpServletRequest request, HttpServletResponse response) {
ServletContext application = request.getSession().getServletContext();
//这里的文件是“写死的”,可以根据用户的请求来获取具体要下载的文件路径
String realPath = application.getRealPath("files");
String fullPath = realPath + File.separator + "test.xls";

//关键点
response.setContentType("application/vnd.ms-excel");
try {
File downloadFile = new File(fullPath);
FileInputStream inputStream = new FileInputStream(downloadFile);
IOUtils.copy(inputStream, response.getOutputStream());
response.flushBuffer();
} catch (IOException e) {
e.printStackTrace();
}
}