HttpServletResponse对象的两个流
- response.getWriter().write
@ResponseBody
@GetMapping("/write")
public User write(){
return new User(1,"zs");
}
先来看这段代码,@ResponseBody注解的作用是将方法的返回值以JSON的形式写入到响应体中。也就是以上的代码可换成如下形式,其作用是等价的。
@GetMapping("/write2")
public void write2(HttpServletResponse response) throws Exception {
response.setContentType("application/json");
response.getWriter().write(JSON.toJSONString(new User(1,"zs")));
}
但是注意,这种写法是错误的。
@GetMapping("/write3")
public User write3(HttpServletResponse response) throws Exception {
response.setContentType("application/json");
response.getWriter().write(JSON.toJSONString(new User(1,"zs")));
return new User(2,"ls");
}
由于response.getWriter().write方法已经将响应体中的内容写出了,此时浏览器与服务器的Socket链接已经关闭,而return new User(2,“ls”);时相当于又一次调用了write方法,但write方法已经调用过,关闭了,所以报了如下错误。
- response.getWriter().write
我们使用这个write方法也能将响应体中的内容写出
@GetMapping("/output1")
public void output1(HttpServletResponse response) throws Exception {
response.setContentType("application/json;charset=utf-8");
response.getOutputStream().write(JSON.toJSONString(new User(1,"zs")).getBytes());
}
在多次调用输出流方法时,要注意响应体类型,如下代码会报错
@GetMapping("/output1")
public void output1(HttpServletResponse response) throws Exception {
response.setContentType("application/json");
response.getOutputStream().write(JSON.toJSONString(new User(1,"zs")).getBytes());
response.getOutputStream().write(JSON.toJSONString(new User(1,"zs")).getBytes());
}
这里报了一个JSON解析错误,因为连续调用了两次write,输出了两个json字符串,这样应该组成一个json数组。而如果是一个json数组的话,我i们应该修改为这样
@GetMapping("/output1")
public void output1(HttpServletResponse response) throws Exception {
response.setContentType("application/json");
response.getOutputStream().write("[".getBytes());
response.getOutputStream().write(JSON.toJSONString(new User(1,"zs")).getBytes());
response.getOutputStream().write(",".getBytes());
response.getOutputStream().write(JSON.toJSONString(new User(1,"zs")).getBytes());
response.getOutputStream().write("]".getBytes());
}
或者直接将响应类型修改为普通文本类型
总结:如果响应一次,例如响应一个json,一般用response.getWrite().write(),如果是响应一个输出流,例如响应一张图片,一个文件,就用response.getOutputStream().write()