Springmvc-將前端資料對映成JAVA物件接收例項
阿新 • • 發佈:2019-01-28
確保前端資料欄位 跟 JAVA物件屬性(欄位) 一致
JQ程式碼:
//前端資料
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請求
$.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) {
....
}
});
JAVA程式碼:
/**
* 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;
}
@RequestBody SetGoodsSpecDTO :將請求資料對映到物件,@RequestBody註解至關重要
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實體類屬性(欄位) 一致