一、前后端传递和接受json数据
1. 使用Ajax默认格式来传递数据【推荐】
Ajax的默认格式为:application/x-www-form-urlencoded,相当于(username="admin"&password=123)来传递数据(这是GET请求的固定格式)
前端代码:
当Ajax以默认格式上传时,data数据直接使用JSON对象user,不用转换为JSON字符串(很方便)
var user= {
"username" : username,
"password" : password,
"rememberMe":rememberMe
};
$.ajax({
url : "http://...../jsontest.do",
type : "POST",
async : true,
data : user,
dataType : 'json',
success : function(data) {
}
});
后端使用@RequestParam注解或省略:
【推荐】
//直接省略注解
@RequestMapping("/jsontest.do")
public void test(User user,String username,String password,Boolean rememberMe){
System.out.println(user);
System.out.println("username: " + username);
System.out.println("password: " + password);
System.out.println("rememberMe: " + rememberMe);
}
【不推荐】
//加上注解
@RequestMapping("/jsontest.do")
public void test(@RequestParam String username,
@RequestParam String password,@RequestParam Boolean rememberMe,){
System.out.println("username: " + username);
System.out.println("password: " + password);
System.out.println("rememberMe: " + rememberMe);
}
优点:
1.前端传递数据不用转换为json字符串:JSON.stringify(user)
2.后端接受的参数很灵活,即可以封装为User对象,亦可以使用单个参数username,rememberMe,甚至User对象和单个rememberMe参数混合使用都可以
2. 使用application/json格式来传递数据
Content-Type使用application/json的时候,要将JSON对象转换为JSON字符串
前端代码:
var user= {
"username" : username,
"password" : password
};
$.ajax({
url : "http://...../jsontest.do",
type : "POST",
async : true,
contentType: "application/json; charset=utf-8",
data : JSON.stringify(user),
dataType : 'json',
success : function(data) {
}
});
后端必须使用@RequestBody 注解:
//这种方式下所有的参数都只能封装在User对象中,不能单独设置参数
@RequestMapping("/jsontest")
public void test(@RequestBody User user ){
String username = user.getUsername();
String password = user.getPassword();
}
或者
@RequestMapping("/jsontest")
public void test(@RequestBody Map map ){
String username = map.get("username").toString();
String password = map.get("password").toString();
}
或者
public void test(@RequestBody String jsonData) {
JSONObject jsonObject = JSON.parseObject(jsonData);
String username= jsonObject.getString("username");
String username= jsonObject.getString("password");
}
缺点:
1.前端需要使用JSON.stringify()将JSON对象转换为JSON字符串
2.后端在接受参数的时候比较麻烦,没有第1种简单,也没有第一种灵活
二、 spring-web.xml中需要如下配置
text/html;charset=UTF-8
application/json;charset=UTF-8
application/xml;charset=UTF-8
AllowArbitraryCommas
AllowUnQuotedFieldNames
DisableCircularReferenceDetect