Springmvc-将前端数据映射成JAVA对象接收实例

确保前端数据字段 跟 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) {
                  ....
             }
         });

JSON.stringify():将一个JavaScript值转换为一个JSON字符串
资料链接:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

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 map = new HashMap();
        List 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> specList;

    public SetGoodsSpecDTO() {
    }

    public List> getSpecList() {
        return this.specList;
    }

    public void setSpecList(List> 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实体类属性(字段) 一致

你可能感兴趣的:(Springmvc)