使用Json進行前後臺傳值
一、傳值方式
Json通過字串形式進行前後臺傳值
二、Jsp_Servlet_前後臺傳值
- 從前臺向後臺傳值:使用x-www-form-urlencoded:request.getParameter()方法獲取json欄位
使用application/json編碼格式,json字串以流的形式傳輸。使用BufferedReader讀取流資料並存入字串中,最後使用JSONObject.toBean()方法將json字串填充到Pojo類物件中。
BufferedReader br = request.getReader(); String str, wholeStr = ""; while((str = br.readLine()) != null){ wholeStr += str; } System.out.println(wholeStr); User user= (User) JSONObject.toBean(JSONObject.fromObject(wholeStr),User.class); System.out.println(user.getUsername());
- 從後臺向前臺傳值:通過response物件獲得PrintWriter物件直接向客戶端輸出json字串
示例:Prinwriter out=response.getPrintWriter();
out.print(JSONObject.toString());
三、Springmvc_前後臺傳值
- 從前臺向後臺傳值:使用Springmvc預設轉換機制,在controller方法頭通過@requestParam、@requestBody或無註解方式填充
@requestParam:常處理content-Type為x-www-form-urlencoded型別的編碼格式,x-www-form-urlencode編碼格式本質將 請求引數轉換成鍵值對形式,等價於request.getParameter()方法,可進行數 據型別轉化(如字串型別填充到pojo類物件中),常用來繫結單個引數
@requestBody:常用來處理content-Type不是x-www-form-urlencoded型別的編碼格式,如:application/json,只能接受json字串,所以前臺Ajax需要進行Json.stringfy()序列化轉化或加單引號變為json字串,同@requestParam,可進行資料型別填充轉化。
無註解:常用來pojo物件的填充
- 從後臺向前臺傳值: 1.使用Springmvc資料轉換機制,返回List、Map等集合類,springmvc自動將其轉成json字串
2.直接返回json字串,建立JSONObject物件,返回JSONObject.toString();