這里講解的使用spring支持的第三方jar包的使用來處理json數據,不包括其他的方法。
響應json數據:
這里涉及了幾種比較復雜的json數據的響應;
第一步導包:
第二步單純的響應json數據:
1 /** 2 * 3 */ 4 package com.sxt.controller; 5 6 import java.util.ArrayList; 7 import java.util.Arrays; 8 import java.util.HashMap; 9 import java.util.List; 10 import java.util.Map; 11 12 import org.springframework.stereotype.Controller; 13 import org.springframework.web.bind.annotation.RequestMapping; 14 import org.springframework.web.bind.annotation.ResponseBody; 15 /** 16 * @author ASUS 17 * 利用gson響應json數據 18 * 19 * 20 */ 21 22 import com.sxt.bean.User; 23 @Controller 24 public class MyController { 25 /** 26 * 響應一個map集合的數據轉換成json 27 * @return 28 */ 29 @RequestMapping("/fun1") 30 @ResponseBody 31 public Map<String, Object> fun1(){ 32 Map<String, Object> map=new HashMap<>(); 33 map.put("id", 1); 34 map.put("name", "張三"); 35 map.put("age", 20); 36 map.put("address", "深圳尚學堂"); 37 return map; 38 } 39 /** 40 * 響應一個list數據的 41 * @return 42 */ 43 @RequestMapping("/fun2") 44 @ResponseBody 45 public List<String> fun2(){ 46 System.out.println("------------"); 47 return Arrays.asList("深圳","廣州","上海","北京"); 48 } 49 @RequestMapping("/fun3") 50 @ResponseBody 51 public User fun3() { 52 User user=new User(); 53 user.setUsername("ass"); 54 user.setPassword("122"); 55 return null; 56 } 57 @RequestMapping("/fun4") 58 @ResponseBody 59 public Map<String, Object> fun4(){ 60 Map<String, Object> map=new HashMap<>(); 61 map.put("total", 20); 62 List<User> list = new ArrayList<>(); 63 for(int i =0;i<5;i++){ 64 User user = new User(); 65 user.setUsername("aaa"+i); 66 user.setPassword("bbbb"+i); 67 list.add(user); 68 } 69 map.put("rows", list); 70 return map; 71 } 72 73 }
上面的案例中還可以把@ResponseBody添加到類的頭上,這表明該類就是一個專門的響應json數據的類
二:接收json數據
controller代碼:
1 /** 2 * 3 */ 4 package com.sxt.controller; 5 6 import org.springframework.stereotype.Controller; 7 import org.springframework.web.bind.annotation.RequestBody; 8 import org.springframework.web.bind.annotation.RequestMapping; 9 import org.springframework.web.bind.annotation.ResponseBody; 10 11 import com.sxt.bean.User; 12 13 /** 14 * @author ASUS 15 * 獲取請求的json數據 16 * 17 */ 18 @Controller 19 public class RequestJson { 20 @RequestMapping("/add") 21 @ResponseBody 22 public String add(@RequestBody User user) { 23 System.out.println(user); 24 return "/index.jsp"; 25 } 26 }
注意:這里多了一個注解;該注解能把請求的json數據自動轉換成對象數據
還可以用@RestController來代替@Controller和@ResponseBody的功能
jsp頁面代碼:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <% 4 String path = request.getContextPath(); 5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 6 %> 7 <!DOCTYPE html> 8 <html> 9 <head> 10 <base href="<%=basePath%>"> 11 <meta charset="UTF-8"> 12 <title>Insert title here</title> 13 <script type="text/javascript" src="js/jquery.min.js"></script> 14 </head> 15 <body> 16 <input type="button" value="提交數據" onclick="fun1();"> 17 <script type="text/javascript"> 18 function fun1() { 19 $.ajax({ 20 type : 'POST', 21 url : "add", 22 contentType : "application/json", 23 //如果想以json格式把數據提交到后台的話,這個必須有,否則只會當做表單提交 24 data : JSON.stringify({ 25 "username" : "aaa", 26 "password" : "bbb" 27 }),//JSON.stringify()必須有,否則只會當做表單的格式提交 28 dataType : "json",//期待返回的數據類型 29 success : function(data) { 30 alert("success:" + data); 31 }, 32 error : function(data) { 33 alert("error" + data); 34 } 35 }); 36 } 37 </script> 38 </body> 39 </html>
注意:如果我們在接收json數據的時候加上@RequestBody這個注解,那么它會自動將請求的json數據轉換到對象中。
在我們日常的開發中,404,500這類的錯誤異常信息屢見不鮮;這是因為在開發中的異常信息都被我們try-catch給處理掉了,所以當某一個出現問題的就會拋出這樣的界面;
這樣給用戶的體驗很不好。在spring中有一個專門的異常處理器HandlerExceptionResolver,我們可以借助這個接口將錯誤的界面換成更好看的界面展示給客戶。但是,這存在一個問題,也就是我們所有的異常必須往上拋,最后再controller中利用該接口展示給用戶我們想讓他們看到的界面。
第一步:
創建一個異常處理器實現HandlerExceptionResolver接口
代碼:
1 /** 2 * 3 */ 4 package com.sxt.controller; 5 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 import org.springframework.stereotype.Component; 9 import org.springframework.web.servlet.HandlerExceptionResolver; 10 import org.springframework.web.servlet.ModelAndView; 11 /** 12 * @author ASUS 13 * 自定義的全局異常處理器 14 * 15 */ 16 @Component 17 public class MyHandleException implements HandlerExceptionResolver{ 18 19 /** 20 * ex就是對應的拋出的按個異常 21 */ 22 @Override 23 public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, 24 Exception ex) { 25 // TODO Auto-generated method stub 26 System.out.println(ex); 27 System.out.println(ex.getMessage()); 28 ModelAndView mc=new ModelAndView(); 29 mc.setViewName("/error.jsp"); 30 return mc; 31 } 32 33 }
在controller中對異常進行展示:
1 /** 2 * 3 */ 4 package com.sxt.controller; 5 6 7 8 import org.springframework.stereotype.Controller; 9 import org.springframework.web.bind.annotation.RequestMapping; 10 11 import com.sxt.bean.User; 12 import com.sxt.exception.CustomException; 13 /** 14 * @author ASUS 15 * 將異常全部拋出,最后再controller中有一個spring自帶的異常處理器;如果不拋的話就沒有辦法知道這些異常 16 * 用戶就可能見到404這樣的異常信息,為了更好地體驗,我們將這樣的錯誤界面換成更好看的,這在顯示生活中很常見 17 * 18 */ 19 @Controller 20 public class MyController { 21 @RequestMapping("/update") 22 public String update( User user) throws CustomException { 23 System.out.println("------------"); 24 System.out.println(user); 25 if("admin".equals(user.getUsername())) { 26 throw new CustomException("系統維護,請稍后訪問!!"); 27 }else if("root".equals(user.getUsername())) { 28 throw new CustomException("類型出錯了"); 29 } 30 return "/user.jsp"; 31 } 32 33 }
自定義異常信息顯示類:
1 /** 2 * 3 */ 4 package com.sxt.exception; 5 6 /** 7 * @author ASUS 8 * 自定義異常類 9 * 10 */ 11 public class CustomException extends Exception{ 12 13 /** 14 * 15 */ 16 private static final long serialVersionUID = 1L; 17 private String message; 18 public String getMessage() { 19 return message; 20 } 21 public void setMessage(String message) { 22 this.message = message; 23 } 24 @Override 25 public String toString() { 26 return "CustomException [message=" + message + "]"; 27 } 28 29 public CustomException(String message) { 30 super(message); 31 this.message=message; 32 } 33 34 35 }
錯誤界面代碼:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <% 4 String path = request.getContextPath(); 5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 6 %> 7 <!DOCTYPE html> 8 <html> 9 <head> 10 <base href="<%=basePath%>"> 11 <meta charset="UTF-8"> 12 <title>Insert title here</title> 13 </head> 14 <body> 15 錯誤頁面!!! 16 </body> 17 </html>
配置文件信息:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:mvc="http://www.springframework.org/schema/mvc" 6 xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd 7 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 8 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> 9 10 <!-- 開啟注解 --> 11 <mvc:annotation-driven ></mvc:annotation-driven> 12 <!-- 開啟掃描 --> 13 <context:component-scan base-package="com.sxt.*"></context:component-scan> 14 15 16 </beans>
注意:這里使用的是注解的形式,如果在自定義異常處理器中沒有使用注解,就要在spring-mvc.xml文件中配置異常處理器