Content-Type为application/json后台如何接收前台数据

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)

第二种情况在servlet下

处理方法为前台传输数据依旧需要从json对象转成json字符串data: JSON.stringify({name:'wyc',age:12})

后台定义一个类包含name和age属性:

public class user {
    String userName;
    String password;
    省略get和set方法

}

后台接收函数为

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());
}



你可能感兴趣的:(Content-Type为application/json后台如何接收前台数据)