簡體   English   中英

如何將整數數組傳遞給spring控制器?

[英]How do I pass an array of integer into spring controller?

腳本Array int和我希望傳遞給Spring Controller 但我一直在

400 bad request.

如果我的js array

array = [1,2,3,4]
array -> 400 bad request
JSON.Stringify(array) -> I will get [1,2,3,4]

    $.ajax({//jquery ajax
                data:{"images": array},                
                dataType:'json',
                type:"post",
                url:"hellomotto"
                ....
            })

當我循環string List ..第一個元素將是'[1'

@RequestMapping(value = "/hellomotto", method = Request.POST)
public void hellomotto(@RequestParam("images") List<String> images){
 sysout(images); -> I will get [1,2,3,4]
}

公共無效

我可以知道如何正確地做到這一點? 我嘗試過不同的組合

以下是一個工作示例:

使用Javascript:

$('#btn_confirm').click(function (e) {

    e.preventDefault();     // do not submit the form

    // prepare the array
    var data = table.rows('.selected').data();
    var ids = [];
    for(var i = 0; i < data.length; i++) { 
        ids.push(Number(data[i][0]));
    }

    $.ajax({
        type: "POST",
        url: "?confirm",
        data: JSON.stringify(ids),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data){
            alert(data);
        },
        failure: function(errMsg) {
            alert(errMsg);
        }
    });
});

控制器:

@RequestMapping(params = "confirm", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody int confirm(@RequestBody Long[] ids) {
    // code to handle request
    return ids.length;
}

@RequestParam用於綁定請求參數,所以如果你做了類似的事情

@RequestMapping(value = "/hellomotto", method = Request.POST)
public void hellomotto(@RequestParam("image") String image){
     ...
}

你發布到/ hellomotto?image = test,hellomotto方法中的圖像變量將包含“test”

你想要做的是解析Request body,所以你應該使用@RequestBody注釋:

http://docs.spring.io/spring/docs/3.0.x/reference/mvc.html#mvc-ann-requestbody

它使用jackson labrary(因此你必須將它作為你的依賴項包含在內)來將json對象解析為java對象。

我想你想要Ajax調用,通過ajax,你發送整數列表所以在春天你的控制器將是

@RequestMapping(value = "/hellomotto", method = Request.POST)
@ResponseBody
public void hellomotto(@RequestParam("images") List<Integer> images){
 sysout(images); -> I will get [1,2,3,4]
}

*您的代碼中缺少@ResponseBody

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM