controller 输出流
时间: 2023-08-01 07:06:20 浏览: 58
Controller 输出流指的是在 MVC(Model-View-Controller)架构中,Controller 层输出的数据流。在 Controller 层中,经常需要将处理完的数据发送到前端页面或其他后端模块,这时就需要使用输出流将数据发送出去。通常情况下,Controller 输出流可以使用 Servlet API 中提供的 HttpServletResponse 对象来实现。
在使用 HttpServletResponse 输出流时,通常需要先设置响应头信息,包括 Content-Type、Content-Disposition、Content-Length 等,然后再通过 getOutputStream() 方法获取输出流,将数据写入输出流中,最后关闭输出流即可。示例代码如下:
```java
@RequestMapping("/download")
public void download(HttpServletResponse response) throws IOException {
// 设置响应头信息
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=test.txt");
response.setHeader("Content-Length", "1024");
// 获取输出流
OutputStream out = response.getOutputStream();
// 将数据写入输出流中
out.write("Hello World!".getBytes());
// 关闭输出流
out.close();
}
```
上述代码中,我们定义了一个 download() 方法,在该方法中设置了响应头信息,并通过 getOutputStream() 方法获取输出流。然后将字符串数据 "Hello World!" 写入输出流中,最后关闭输出流。这样就可以将数据发送到前端页面或其他后端模块。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)