如何在Spring中传递多个请求参数?

时间:2013-07-13 04:45:15

标签: java jquery ajax spring

在我的Spring应用程序中,我将两个请求参数传递给我的业务逻辑..

$.ajax({
        url : "classes/addResult",
        type:'POST',
        data : {"names":names,"globalClassId":globalClassId}

    });

我的业务逻辑

@RequestMapping(value = "addResult", method = RequestMethod.POST)
public String addResult(ResultForm form,
        BindingResult result, Model model,
        @RequestParam("names") String[] names,
        @RequestParam("globalClassId") String globalClassId)
        throws Exception {
        -------------
        ------------
    return "";
}

但是控制器没有调用这个方法..为什么他们的代码有任何错误..

2 个答案:

答案 0 :(得分:2)

<script type="text/javascript">
   var names = new Array();
    $.ajax({
        url : "Result",
        type : 'POST',
        data : {
            "names" : JSON.stringify(names),//or names.join()
            "globalClassId" : globalClassId
        }});
</script>

答案 1 :(得分:1)

如果您收到错误400(错误请求)????????????

当您将数组数据(在您的情况下为{names:names})传递给$ .ajax()方法时,它会在paremeter名称后附加squre括号[]表示名称为[] //而不是名称)

因此,您需要对代码进行一些更改

@RequestMapping(value = "addResult", method = RequestMethod.POST)
public String addResult(ResultForm form,
        BindingResult result, Model model,
        @RequestParam("names[]") String[] names, //replace names with names[]
        @RequestParam("globalClassId") String globalClassId)
        throws Exception {
        -------------
        ------------
    return "";
}

或者您可以使用

@RequestMapping(value = "addResult", method = RequestMethod.POST)
    public String addResult(ResultForm form,
            BindingResult result, Model model,
            @RequestParam("globalClassId") String globalClassId)
            throws Exception {
        String[] names = request.getParameterValues("names[]");//getting names array here
            -------------
            ------------
        return "";
    }