如何使用Ajax调用Spring MVC Controller传递List

时间:2017-11-27 03:31:26

标签: javascript ajax spring-mvc

我持有对象如下:

public class Transfer implements Serializable {
     private Integer transferId;
     private Integer transferTypeId;
     private String storeId;
     private String userId;
     private Integer titleId;
     private Integer statusId;
     private String inWorkerId;
     private String outWorkerId;
     private Date createDt;
     private Date updateDt;
     // getters & setts
 }

我需要将var reqRow发送到控制器

function onClickSave(){
    var rows = $('#transferEditGrid').jqGrid('getRowData');
    var reqRow = [];
    for (i = 0; i < rows.length; i++)
    {
        var rowObj = {};
        rowObj.storeId = rows[i].storeId;
        rowObj.inWorkerId = rows[i].inWorkerId;
        rowObj.outWorkerId = rows[i].outWorkerId;
        rowObj.transferTypeId = rows[i].transferTypeId;
        rowObj.statusId = rows[i].statusId;
        rowObj.storeId = rows[i].storeId;
        reqRow.push(rowObj);
    }

    //send reqRow to the Controller
    $.ajax({
        type:'POST',
        url:'${contextPath}/resource-transfer/update.do',
        dataType:"json",
        data : {rows : reqRow},
        //data:JSON.stringify(reqRow),
        success:function(response){
            alert("success");

        }
    });
}

控制器如下:

@RequestMapping(value = "/update", method = { RequestMethod.GET, RequestMethod.POST }, produces = "application/json; charset=utf-8")
@ResponseBody
public String transferUpdate(@RequestBody List<Transfer> rows) throws JSONException, InterruptedException {

    System.out.println("in transfer update section");

    return null;
}

为什么我无法将数组对象传递给控制器​​? 我是否误解了Ajax调用的用法?

谢谢

2 个答案:

答案 0 :(得分:0)

  1. 首先,将List包装到另一个java对象

    public class TransferDTO {
       private List<Transfer> rows;
       // getter & setter
     }
    
  2. 在您的终端中使用此List<Transfer>

  3. public String transferUpdate(@RequestBody TransferDTO data)

    1. 在AJAX帖子中指定contentType
    2. contentType: 'application/json'

      1. 手动字符串化数据
      2. data : JSON.stringify({rows: reqRow})

答案 1 :(得分:0)

Java代码

@Controller
public class ContractController {

    @RequestMapping(value="all/contract/change/detail", method = RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public List<ContractAndBidReceiveChangeDetailModel> getAllContractAndBidReceiveChangeDetail(@RequestBody List<ContractReceivedChangedActivityCodesModel> allChangedActivityCodesModel) {

        List<ContractAndBidReceiveChangeDetailModel> allContractAndBidChangeDetails = null;

        if (CollectionUtils.isNotEmpty(allChangedActivityCodesModel)) {
            allContractAndBidChangeDetails = allChangedActivityCodesModel
                    .stream()
                    .map(this::getContractAndBidReceiveChangeDetail)
                    .collect(Collectors.toList());
        }

        return allContractAndBidChangeDetails;
    }
} // end of controller class

@JsonAutoDetect(
    creatorVisibility = JsonAutoDetect.Visibility.NONE,
    fieldVisibility = JsonAutoDetect.Visibility.NONE,
    getterVisibility = JsonAutoDetect.Visibility.NONE,
    isGetterVisibility = JsonAutoDetect.Visibility.NONE,
    setterVisibility = JsonAutoDetect.Visibility.NONE
)
public class ContractReceivedChangedActivityCodesModel {

    private String rowId;
    private Long bidId;
    private Long planId;
    private Long optionCodeId;
    private Long activityCodeId;
    private Long activityPackageId;
    private String activityCodeNoAndName;
    private String planName;

    // constructors

    @JsonProperty
    public String getRowId() {
        return rowId;
    }

    public void setRowId(String rowId) {
        this.rowId = rowId;
    }

    //others getters and setters
}

jQuery代码。确保您进行了与Spring预期相同的json rquest。 Spring会自动将此json映射到您的Java列表

function getDetailRow(url, requestData, $caret, action) {

    $spinner.show();

    $.ajax({ 
        url: url, 
        data : requestData,
        dataType: "json",
        type: "POST",
        contentType: "application/json",
        success: function(response) {
            if (!$.isEmptyObject(response)) {
                switch(action){
                    case "expandLink":
                        insertDetailRow($caret, response);
                    break;
                    case "expandAllLinks":
                        $.each(response, function(index, changeDetailResponse) {
                            var caretId = changeDetailResponse.rowId;
                            let $caret = $('#' + caretId);
                            insertDetailRow($caret, changeDetailResponse);  
                        });
                    break;
                }
            } 
            $spinner.hide();
        }, error: function(xhr, status, error){
            $spinner.hide();
            if (xhr.status == 500) {
                var errorResponse = xhr.responseText;
                if (errorResponse) {
                    alert(errorResponse);
                }
            }
        }
    });
}

function getRequestJson(requestObject) {        
    let requestJson = null;
    if (requestObject != null) {
        requestJson = JSON.stringify(requestObject);
    }
    return requestJson;
}

function getRequestObject($caret) {
    let requestObject = null;
    if ($caret.length > 0) {
        let rowId = $caret.attr("id");
        let bidId = $caret.attr("bidId");
        let planId = $caret.attr("planId");
        let optionCodeId = $caret.attr("optionCodeId");
        let activityCodeId = $caret.attr("activityCodeId");
        let activityPackageId = $caret.attr("activityPackageId");

        requestObject = new Object();
        requestObject.rowId = rowId;
        requestObject.bidId = bidId;
        requestObject.planId = planId;  
        requestObject.optionCodeId = optionCodeId;
        requestObject.activityCodeId = activityCodeId;
        requestObject.activityPackageId = activityPackageId;    
    }
    return requestObject;
}

let caretsWithoutDetailRow = new Array();
let requestObjects = null;

// process caretsWithoutDetailRow Array with some logic so it contains some elements

if (caretsWithoutDetailRow.length > 0) {
    requestObjects = new Array();
    $.each(caretsWithoutDetailRow, function(index, $caret) {
        let requestObject = getRequestObject($caret);
        requestObjects.push(requestObject);
    });
}

if (requestObjects != null && requestObjects.length > 0) {
    let requestObjectsJson = getRequestJson(requestObjects);
    let url = '<c:url value = "/all/contract/change/detail"/>';
    getDetailRow(url, requestObjectsJson, null, 'expandAllLinks');
}