一、后台返回的數據轉換成json
1、引入轉換json需要的3個依賴
1 <!--json轉換需要的依賴 begin --> 2 <dependency> 3 <groupId>com.fasterxml.jackson.core</groupId> 4 <artifactId>jackson-annotations</artifactId> 5 <version>2.9.2</version> 6 </dependency> 7 <dependency> 8 <groupId>com.fasterxml.jackson.core</groupId> 9 <artifactId>jackson-core</artifactId> 10 <version>2.9.1</version> 11 <type>jar.sha256</type> 12 </dependency> 13 <dependency> 14 <groupId>com.fasterxml.jackson.core</groupId> 15 <artifactId>jackson-databind</artifactId> 16 <version>2.9.2</version> 17 </dependency> 18 <!--json轉換需要的依賴 end -->
2、寫handle
一定要加上注解@ResponseBody
1 @ResponseBody 2 @RequestMapping("/testJson") 3 public Collection<Employee> testJson(){ 4 return employeeDao.getAll(); 5 }
3、在index.jsp用ajax發請求
1 <script type="text/javascript" src="scripts/jquery-1.9.1.min.js"></script> 2 <script type="text/javascript"> 3 $(function(){ 4 $("#testJson").click(function(){ 5 var url = this.href; 6 var args = {}; 7 $.post(url, args, function(data){ 8 for(var i = 0; i < data.length; i++){ 9 var id = data[i].id; 10 var lastName = data[i].lastName; 11 12 alert(id + ": " + lastName); 13 } 14 }); 15 return false; 16 }); 17 }) 18 </script> 19 </head> 20 <body> 21 22 <a href="testJson" id="testJson">Test Json</a> 23 </body> 24 </html>
查看請求響應結果
[
{"id":1001,"lastName":"E-AA","email":"aa@163.com","gender":1,"department":{"id":101,"departmentName":"D-AA"},"birth":null,"salary":null},
{"id":1002,"lastName":"E-BB","email":"bb@163.com","gender":1,"department":{"id":102,"departmentName":"D-BB"},"birth":null,"salary":null},
{"id":1003,"lastName":"E-CC","email":"cc@163.com","gender":0,"department":{"id":103,"departmentName":"D-CC"},"birth":null,"salary":null},
{"id":1004,"lastName":"E-DD","email":"dd@163.com","gender":0,"department":{"id":104,"departmentName":"D-DD"},"birth":null,"salary":null},
{"id":1005,"lastName":"E-EE","email":"ee@163.com","gender":1,"department":{"id":105,"departmentName":"D-EE"},"birth":null,"salary":null}
]
4、原理分析:使用HttpMessageConverter<T>轉換
• HttpMessageConverter<T> 是 Spring3.0 新添加的一個接口,負責將請求信息轉換為一個對象(類型為 T),將對象(類型為 T)輸出為響應信息。
• 使用 HttpMessageConverter<T> 將請求信息轉化並綁定到處理方法的入參中或將響應結果轉為對應類型的響應信息,Spring 提供了兩種途徑:
– 使用 @RequestBody / @ResponseBody 對處理方法進行標注
– 使用 HttpEntity<T> / ResponseEntity<T> 作為處理方法的入參或返回值
• 當控制器處理方法使用到 @RequestBody/@ResponseBody 或HttpEntity<T>/ResponseEntity<T> 時, Spring 首先根據請求頭或響應頭的Accept 屬性選擇匹配的 HttpMessageConverter, 進而根據參數類型或泛型類型的過濾得到匹配的 HttpMessageConverter, 若找不到可用的HttpMessageConverter 將報錯
• @RequestBody 和 @ResponseBody 不需要成對出現
原理圖如下:
二、文件下載
1. 編寫handle
1 @RequestMapping("/testResponseEntity") 2 public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException{ 3 byte [] body = null; 4 ServletContext servletContext = session.getServletContext(); 5 InputStream in = servletContext.getResourceAsStream("/files/abc.txt"); 6 body = new byte[in.available()]; 7 in.read(body); 8 9 HttpHeaders headers = new HttpHeaders(); 10 headers.add("Content-Disposition", "attachment;filename=abc.txt"); 11 12 HttpStatus statusCode = HttpStatus.OK; 13 14 ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body, headers, statusCode); 15 return response; 16 }
2.在jsp頁面發請求
1 <a href="testResponseEntity">Test ResponseEntity</a>
三、文件上傳
• Spring MVC 為文件上傳提供了直接的支持,這種支持是通過即插即用的 MultipartResolver 實現的。Spring 用Jakarta Commons FileUpload技術實現了一個
MultipartResolver 實現類:CommonsMultipartResovler
• Spring MVC 上下文中默認沒有裝配 MultipartResovler,因此默認情況下不能處理文件的上傳工作,如果想使用 Spring 的文件上傳功能,需現在上下文中配置 MultipartResolver
1.在pom.xml引入文件上傳需要的依賴
1 <dependency> 2 <groupId>commons-fileupload</groupId> 3 <artifactId>commons-fileupload</artifactId> 4 <version>1.2.1</version> 5 </dependency> 6 <dependency> 7 <groupId>commons-io</groupId> 8 <artifactId>commons-io</artifactId> 9 <version>2.0</version> 10 </dependency>
2.springmvc.xml里面配置MultipartResolver
• defaultEncoding: 必須和用戶 JSP 的 pageEncoding 屬性一致,以便正確解析表單的內容
• 為了讓 CommonsMultipartResovler 正確工作,必須先將 Jakarta Commons FileUpload 及 Jakarta Commons io的類包添加到類路徑下。
1 <!-- 配置 MultipartResolver --> 2 <bean id="multipartResolver" 3 class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 4 <property name="defaultEncoding" value="UTF-8"></property> 5 <property name="maxUploadSize" value="1024000"></property> 6 </bean>
3.編寫handle
1 @RequestMapping("/testFileUpload") 2 public String testFileUpload(@RequestParam("desc") String desc, 3 @RequestParam("file") MultipartFile file) throws IOException{ 4 System.out.println("desc: " + desc); 5 System.out.println("OriginalFilename: " + file.getOriginalFilename()); 6 System.out.println("InputStream: " + file.getInputStream()); 7 return "success"; 8 }
4.編寫index.jsp
1 <form action="testFileUpload" method="POST" enctype="multipart/form-data"> 2 File: <input type="file" name="file"/> 3 Desc: <input type="text" name="desc"/> 4 <input type="submit" value="Submit"/> 5 </form>