SpringMVC檔案下載與JSON格式(七)
阿新 • • 發佈:2018-12-13
現在JSON這種資料格式是被使用的非常的廣泛的,SpringMVC作為目前最受歡迎的框架,它對JSON這種資料格式提供了非常友好的支援,可以說是簡單到爆。
在我們SpringMVC中只需要新增jackjson的jar包後RequestMappingHandlerAdapter會將MappingJacksonHttpMessageConverter裝配進來。而我們使用也只需要使用註解修飾就可以完成JSON格式的轉換
@ResponseBoy
//@ResponseBody @RequestMapping("/getJson") public @ResponseBody String getJson() {return "success"; }
我們只需要將方法使用註解@ResponseBody修飾就可以完成JSON格式自動轉換,這個註解可以修飾在方法上,也可以修飾在返回值上。我們可以返回任意物件,他會自動轉換成JSON格式返回給客戶端。
ResponseEntity
除了使用@ResponseBody我們還可以使用ResponseEntity物件作為返回值,這兩種方式效果是一樣的。
@RequestMapping("/getJson2") public ResponseEntity<String> getJson2() { ResponseEntity<String> responseEntity = new ResponseEntity<>("<h1>ResponseEntity</h1>", HttpStatus.OK); return responseEntity; }
@RequestBody
該註解用於讀取Request請求的body部分資料,使用系統預設配置的HttpMessageConverter進行解析,然後把相應的資料繫結到要返回的物件上,再把HttpMessageConverter返回的物件資料繫結到 controller中方法的引數上。
<form action="testRequestBody2" method="POST"> <input type="text" name="username"><br> <input type="password" name="userpass"><br> <input type="submit" value="登陸"> </form>
@RequestMapping("/testRequestBody") public String hello(@RequestBody String body) { System.out.println(body); return "hello"; }
他會將我們這個表單中的資料轉換成字串型別
HttpEntity
這個物件使用起來效果是與@RequestBody效果是一致的。
@RequestMapping("/testHttpEntity") public String getJson2(HttpEntity<String> entity) { System.out.println(entity.getBody()); return "hello"; }
檔案下載功能
使用ResponseEntity<byte[]>來實現檔案下載。檔案下載只需要將檔案輸出型別該為可以被下載的檔案型別設定為ResponseEntity<byte[]>即可。
@RequestMapping("/downFile") public ResponseEntity<byte[]> testdownFile(HttpSession session) throws IOException { ServletContext servletContext = session.getServletContext(); InputStream in = servletContext.getResourceAsStream("downloads/down.txt"); byte[] bytes = FileCopyUtils.copyToByteArray(in); HttpHeaders header = new HttpHeaders(); header.add("Content-Disposition", "attachment;filename=down.txt"); ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(bytes, header, HttpStatus.OK); return entity; }
filename這個屬性是檔案下載的檔名字。