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();
}