一、HttpEntity 獲取請求
HttpEntity:可以獲取請求的內容(包括請求頭與請求體)
頁面提交數據:
<form action="${ctp}/testHttpEntity" method="post" enctype="multipart/form-data">
<input name="username" value="tomcat" />
<input name="password" value="123456" />
<input name="file" type="file">
<input type="submit" />
</form>
控制器方法:
/** * 如果參數位置寫 HttpEntity<String> str,可以獲取請求信息 * 不僅可以獲取到請求體,可以獲取到請求頭數據 * * @RequestHeader("") 根據key獲取請求頭 * @param str * @return
*/ @RequestMapping(value = "/testHttpEntity") public String testHttpEntity(HttpEntity<String> str) { System.out.println("HttpEntity:" + str); return "success"; }
輸出:
請求體與請求頭之間會以 逗號 進行分割。
二、ResponseEntity<T> 設置響應
ResponseEntity 用於設置響應頭、響應體與響應狀態碼。
示例:
/** * ResponseEntity<T>: T 響應體內容的類型 * @return
*/ @RequestMapping(value = "/testResponseEntity") public ResponseEntity<String> testResponseEntity() { String body = "<h1>success</h1>"; MultiValueMap<String, String> headers = new HttpHeaders(); headers.add("set-cookie", "username=Tom"); ResponseEntity<String> responseEntity = new ResponseEntity<>(body, headers, HttpStatus.OK); return responseEntity; }
瀏覽器:
利用 ResponseEntity 實現文件下載:
/** * SpringMVC 文件下載 * @param request * @return * @throws Exception */ @RequestMapping(value = "/download") public ResponseEntity<byte[]> fileDown(HttpServletRequest request) throws Exception { //1.獲取下載的文件的流 //獲取文件的真實路徑
String fileName = "jquery-1.8.2.min.js"; ServletContext servletContext = request.getServletContext(); String realPath = servletContext.getRealPath("/js/jquery-1.8.2.min.js"); FileInputStream fileInputStream = new FileInputStream(realPath); //將整個文件放入到 byte 數組中, available() 獲取輸入流所讀取的文件的最大字節數
byte[] tmp = new byte[fileInputStream.available()]; fileInputStream.read(tmp); fileInputStream.close(); //2. 將要下載的文件流返回 //設置請求頭
MultiValueMap<String, String> headers = new HttpHeaders(); headers.add("Content-Disposition", "attachment;filename=" + fileName); //將響應數據到客戶端 // ResponseEntity<T>(T body, MultiValueMap<String,String> headers, HttpStatus statusCode) // body 設置響應體 // headers 設置請求頭 // statusCode 設置響應狀態
ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(tmp, headers, HttpStatus.OK); return responseEntity; }