1.前端Ajax請求方式
(1)Ajax發(fā)送json對象
這種方式是提交的Json對象,contentType為:application/x-www-form-urlencoded,后端可以@RequestParam
var user = {
username : "test",
password:"test"
};
$.ajax({
url:"/addUser.html",
type:"POST",
data:user,
success:function(result) {
console.log(result);
}
});
(2)Ajax發(fā)送字符串(一般對于get請求,post一般不建議)
這種方式contentType為:application/x-www-form-urlencoded,后端可以@RequestParam
$.ajax({
url:"/addUser.html",
type:"GET",
data:"username=test&sex=0",
success:function(result) {
console.log(result);
}
});
這種方式參數(shù)一般較少,并且都是簡單類型
(3)Ajax發(fā)送json字符串
發(fā)送json字符串始锚,有三個地方需要注意类浪,一是要指定type為json,二是要對數(shù)據(jù)JSON.stringify,三是要指定contenType為"contentType:'application/json;charset=UTF-8'
var user = {
username : "test",
password:"test"
};
$.ajax({
url:"/addUser.html",
type:"POST",
type:"json"
data:JSON.stringify(user),
contentType:"application/json;charset=UTF-8",
success:function(result) {
console.log(result);
}
});
2.后端解析方式
(1)第一種方式最铁,直接依次獲取參數(shù),這種方式需要保持和前端傳入?yún)?shù)名稱一致
@RequestMapping("/addUser.html")
public void addUser(String username, String password){
}
(2)第二種方式讯赏,直接依次獲取參數(shù),使用@RequestParam,不要求名稱一致
@RequestMapping("/addUser.html")
public void addUser(@RequestParam(value="username") String name, @RequestParam(value="username") String pwd){
}
(3)第三種方式冷尉,當參數(shù)比較多時漱挎,采用上述方式就比較麻煩,可以定義個pojo來處理
public class User {
private String username;
private String password;
}
@RequestMapping("/addUser.html")
public void addUser(User user){
}
(4)第四種方式雀哨,區(qū)別在于多一個注解@RequestBody
public class User {
private String username;
private String password;
}
@RequestMapping("/addUser.html")
public void addUser(@RequestBody User user){
}
(5)第五種方式磕谅,和第四種類似,使用@ModelAttribute
public class User {
private String username;
private String password;
}
@RequestMapping("/addUser.html")
public void addUser(@ModelAttribute User user){
}
3.使用方式分析
總的原則:使用方式有三個維度:一是參數(shù)少且是簡單類型?二是請求參數(shù)的contentType怜庸?三是是否支持不同名
后端:
- 同名簡單類型当犯,參數(shù)少且contentType為默認contentType為:application/x-www-form-urlencoded,后端直接在方法里通過變量名獲取值
- 不同名簡單類型割疾,參數(shù)少且contentType類型為默認值嚎卫,使用@RequestParam注解
- 復(fù)合類型,contentType默認宏榕,直接使用復(fù)合類型或加上@ModelAttribute注解
- 復(fù)合類型拓诸,contentType不是默認,使用@RequestBody
- 未添加注解的情況下麻昼,默認簡單類型調(diào)用@RequesParam處理奠支,復(fù)雜類型使用@ModelAttribute處理
- @RequestBody的適用情況,有些時候需要發(fā)送前端需要發(fā)送包含數(shù)組的json數(shù)據(jù)抚芦,前端采用第三種方式
前端:
- 看參數(shù)多少和contentType來選擇三種方式