背景:在開發(fā)中特別是做保存邏輯的時候料扰,后端需要接收很多業(yè)務(wù)參數(shù)喂江。
html頁面(上傳的參數(shù)js對象和Java對象對應(yīng)胆敞,js數(shù)組和Java集合對應(yīng)诺祸,字段名字也要對應(yīng)):
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src='jquery-2.1.4.min.js'></script>
</head>
<body>
<button onclick='send()'>try</button>
<script>
function send(){
var obj = new Object();
// 基本信息
var baseInfo = new Object();
baseInfo.name = 'tianye';
baseInfo.age = 18;
baseInfo.sex = '男';
obj.baseInfo = baseInfo;
// 折扣優(yōu)惠
var discount = new Array();
var discountChild1 = new Object();
discountChild1.discountIds = '1,2,3';
discountChild1.productIds = '12,23,45,23';
var discountChild2 = new Object();
discountChild2.discountIds = '12,222,322';
discountChild2.productIds = '122,233,455,2366';
discount.push(discountChild1);
discount.push(discountChild2);
obj.discount = discount;
// 樓棟別名
var product = new Array();
var productChild1 = new Object();
var productChild2 = new Object();
productChild1.id = 222;
productChild1.name = 'sasfds';
productChild1.sort = 2;
productChild2.id = 333;
productChild2.name = 'sfdsfdsfsadf';
productChild2.sort = 1;
product.push(productChild1,productChild2);
obj.product = product;
console.log(obj);
console.log(JSON.stringify(obj));
$.ajax({
url: 'http://localhost:8080/ajax/test1',
type: 'post',
contentType: 'application/json;charset=utf-8',
data: JSON.stringify(obj),
success: function(data){
console.log(data);
console.log(JSON.stringify(data));
}
});
}
</script>
</body>
</html>
Controller處理器:
package com.example.demo.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.example.demo.domain.AjaxDTO;
@Controller
@RequestMapping("/ajax")
public class AjaxController {
@RequestMapping("/test1")
@ResponseBody
public AjaxDTO test1(@RequestBody AjaxDTO AjaxDTO) {
System.out.println(AjaxDTO.getBaseInfo());
System.out.println(AjaxDTO.getDiscount());
System.out.println(AjaxDTO.getProduct());
return AjaxDTO;
}
}
實體Bean
package com.example.demo.domain;
import java.util.List;
public class AjaxDTO {
private BaseInfo baseInfo;
private List<Discount> discount;
private List<Product> product;
// 忽略get携悯,set方法
}
package com.example.demo.domain;
public class BaseInfo {
private String name;
private Integer age;
private String sex;
// 忽略get,set方法
}
package com.example.demo.domain;
public class Discount {
private String discountIds;
private String productIds;
// 忽略get筷笨,set方法
}
package com.example.demo.domain;
public class Product {
private Integer id;
private String name;
private Integer sort;
// 忽略get憔鬼,set方法
}