HttpServletResponse
是 Java Servlet API 提供的一个接口
常用方法
方法 | 用途 |
---|---|
setContentType(String type) | 设置响应内容类型(如 "application/json" 、"text/html" ) |
setStatus(int sc) | 设置响应状态码(如 200、404) |
getWriter() | 获取字符输出流(用于返回文本数据) |
getOutputStream() | 获取字节输出流(用于返回文件、图片等) |
sendRedirect(String location) | 重定向到指定 URL |
addHeader(String name, String value) | 添加响应头 |
setHeader(String name, String value) | 设置响应头(会覆盖已有) |
setCharacterEncoding(String charset) | 设置响应字符编码 |
简单理解
它代表了HTTP 响应对象,用于向客户端返回数据。你可以用它:
-
设置响应头(如
Content-Type
、Cookie
等) -
设置响应状态码(如 200、404)
-
向客户端写出数据(如 HTML、JSON、文件等)
示例:下载文件
@GetMapping("/download")
public void downloadFile(HttpServletResponse response) throws IOException {// 设置响应类型response.setContentType("application/octet-stream");// 设置响应头,告诉浏览器下载文件response.setHeader("Content-Disposition", "attachment; filename=\"test.txt\"");// 写入数据到响应体OutputStream out = response.getOutputStream();out.write("这是一个测试文件".getBytes("UTF-8"));out.flush();out.close();
}