2

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

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?

Thank you

2
  • You need to provide the response. What happened when you send POST request? 400, 404, 500 ? Commented Nov 27, 2017 at 3:37
  • use @RequestParam instead of @RequestBody Commented Nov 27, 2017 at 4:22

2 Answers 2

2
  1. First, wrap List to another java object

    public class TransferDTO {
       private List<Transfer> rows;
       // getter & setter
     }
    
  2. Use this inplace of List<Transfer> in your endpoint.

public String transferUpdate(@RequestBody TransferDTO data)

  1. Specify contentType in your AJAX post

contentType: 'application/json'

  1. Manually stringify the data

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

Sign up to request clarification or add additional context in comments.

1 Comment

I implemented this exactly in my Spring 5 MVC project as described, could NOT get it to work at all. Always get a "Failed to load resource: the server responded with a status of 404 ()" for the controller. Spring 5.1.6
0

Java code

@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. Make sure you make the same json rquest that spring is expecting. Spring will automatically map this json to your java List

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');
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.