SpringMVC-前端数据映射成JAVA对象接收实例
在请求的中将请求的数据与对应的实体类进行相对应完成映射,需要确保请求的数据名称和实体类的名称一致,才可以保证数据完整的映射到实体。
JQUERY代码
//前端数据
var specListArr = new Array();
specList = [];
if ($(this).val() != '') {
var specInfo = {};
specInfo.specName = specName;
specInfo.specValue = $(this).val();
specList.push(specInfo);
}
//specListArr对象数组
specListArr.push(specList)
AJAX的请求
JSON.stringify():将一个JavaScript值转换为一个JSON字符串
//ajax请求
$.ajax({
url: appendSpec_url, //对应请求地址:/seller/goods/appendSpec
type: 'post',
dataType: 'json',
contentType: "application/json", //必须指明请求头类型(关键)
data: JSON.stringify({ //必须将数据格式转换为json字符串格式(关键)
goodsParentId: goodsParentId,
specList: specListArr //specListArr对象数组
}),
success: function (result) {
....
}
});
JAJA代码
@RequestBody SetGoodsSpecDTO :将请求数据映射到对象,@RequestBody注解至关重要
/**
* AJAX追加新商品规格
*
* @param setGoodsSpec SetGoodsSpecDTO对象
* @param request HttpServletRequest对象
* @return map
*/
@ResponseBody
@RequestMapping(value = "/seller/goods/appendSpec")
public Object appendSpec(@RequestBody SetGoodsSpecDTO setGoodsSpec, HttpServletRequest request) {
SetGoodsModel setGoodsModel = new SetGoodsModel();
setGoodsModel.setGoodsParentId(setGoodsSpec.getGoodsParentId());
setGoodsModel.setSpecList(setGoodsSpec.getSpecList());
GetGoodsParentResponse response = gsGoodsParentService.getGoodsInfo(setGoodsModel);
HashMap<String, Object> map = new HashMap<String, Object>();
List<SpecResponse> list = response.getSpecResponseList();
map.put("goodsList", list);
map.put("specArray", list.get(0).getSpecList());
return map;
}
SetGoodsSpecDTO对象(实体类):
public class SetGoodsSpecDTO {
private String goodsParentId;
private List<List<GoodsSpecResponse>> specList;
public SetGoodsSpecDTO() {
}
public List<List<GoodsSpecResponse>> getSpecList() {
return this.specList;
}
public void setSpecList(List<List<GoodsSpecResponse>> specList) {
this.specList = specList;
}
public String getGoodsParentId() {
return this.goodsParentId;
}
public void setGoodsParentId(String goodsParentId) {
this.goodsParentId = goodsParentId;
}
}
特殊说明:
以上针对,数据传输格式为:application/json
当数据传输格式为:
1. x-www-form-urlencoded
2. form-data
JQ 代码不需要使用函数: JSON.stringify()
JAVA 代码不需要使用注解: @RequestBody
确保post / get的数据字段 跟 JAVA实体类属性(字段) 一致
源文章地址
源文章传送门