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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17627056/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 02:30:24  来源:igfitidea点击:

how to pass multiple request parameters in Spring?

javajqueryajaxspring

提问by java

In my Spring Application i'm pass two request parameters to my business logic..

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

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

    });

And my business logic

还有我的业务逻辑

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

But controller not calling to this method .. Why is their is any wrong my code..

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

回答by java

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

回答by vikrant singh

If you are getting error 400 (Bad request) ????????????

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

when you pass array data ({names:names} in your case ) to $.ajax() method then it append squre brackets [] after the paremeter name (means paremeter names will be names[] //not names)

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

therefor you need some changes in your code

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

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


or you can use

或者你可以使用

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