简体   繁体   English

如何使用 Ajax 调用将列表传递给 Spring MVC 控制器

[英]How to Pass List using Ajax call to Spring MVC Controller

I have holding object as follows:我持有的对象如下:

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
 }

And I have var reqRow that need to be sent to the controller我有需要发送到控制器的 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");

        }
    });
}

The controller is following :控制器如下:

@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;
}

Why I could not pass the array object to the controller?为什么我无法将数组对象传递给控制器​​? Did I misunderstand the usage of the Ajax call?我是否误解了 Ajax 调用的用法?

Thank you谢谢

  1. First, wrap List to another java object首先,将List包装到另一个java对象

    public class TransferDTO { private List<Transfer> rows; // getter & setter }
  2. Use this inplace of List<Transfer> in your endpoint.在您的端点中使用此代替List<Transfer>

public String transferUpdate(@RequestBody TransferDTO data)

  1. Specify contentType in your AJAX post在 AJAX 帖子中指定contentType

contentType: 'application/json'

  1. Manually stringify the data手动字符串化数据

data : JSON.stringify({rows: reqRow})

Java code 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 code. jQuery 代码。 Make sure you make the same json rquest that spring is expecting.确保您发出与 spring 相同的 json 请求。 Spring will automatically map this json to your java List 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');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM