Content-Type為application/json時,假設前台傳輸的資料為data: {name:'wyc',age:12}
第一種情況在springmvc架構下
處理方法為前台post請求,傳輸過程中資料需要從json對象轉成json字元串data: JSON.stringify({name:'wyc',age:12})
背景接收函數上添加@requestbody注解,并定義一個類包含name和age屬性:
public class user {
String userName;
String password;
省略get和set方法
}
背景接收函數為
public 方法傳回類型 方法名(@RequestBody user user);
說明@RequestBody注解最好使用對象接收,
也可以通過字元串接收,隻需要定義一個變量就能接收到
public 方法傳回類型 方法名(@RequestBody String data);此時data接收到資料就是{name:'wyc',age:12}(不推薦,因為還要擷取裡面的值,要用json轉換對象等)
第二種情況在servlet下
處理方法為前台傳輸資料依舊需要從json對象轉成json字元串data: JSON.stringify({name:'wyc',age:12})
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
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.getserName());
}
比較麻煩啊,先使用request.getReader();然後再轉成對象user;使用request.getParamer()是接收不到的。