如何将整数数组传递给spring控制器?

时间:2013-10-18 02:10:30

标签: java jquery spring

Array的{​​{1}}脚本,我希望转入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'

public void

我可以知道如何正确地做到这一点?我尝试了不同的组合

3 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:0)

@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对象。

答案 2 :(得分:0)

我认为你想要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

相关问题