在@RequestParam 中绑定列表 [英] Binding a list in @RequestParam

查看:46
本文介绍了在@RequestParam 中绑定列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以这种方式从表单发送一些参数:

I'm sending some parameters from a form in this way:

myparam[0]     : 'myValue1'
myparam[1]     : 'myValue2'
myparam[2]     : 'myValue3'
otherParam     : 'otherValue'
anotherParam   : 'anotherValue' 
...

我知道我可以通过添加类似的参数来获取控制器方法中的所有参数

I know I can get all the params in the controller method by adding a parameter like

public String controllerMethod(@RequestParam Map<String, String> params){
    ....
}

我想将参数 myParam[](而不是其他参数)绑定到列表或数组(任何保持索引顺序的东西),所以我尝试了如下语法:

I want to bind the parameters myParam[] (not the other ones) to a list or array (anything that keeps the index order), so I've tried with a syntax like:

public String controllerMethod(@RequestParam(value="myParam") List<String> myParams){
    ....
}

public String controllerMethod(@RequestParam(value="myParam") String[] myParams){
    ....
}

但它们都没有绑定 myParams.即使我向地图添加一个值,它也无法绑定参数:

but none of them are binding the myParams. Even when I add a value to the map it is not able to bind the params:

public String controllerMethod(@RequestParam(value="myParam") Map<String, String> params){
    ....
}

是否有任何语法可以将一些参数绑定到列表或数组,而不必创建一个包含列表属性的 @ModelAttribute 对象?

Is there any syntax to bind some params to a list or array without having to create an object as @ModelAttribute with a list attribute in it?

谢谢

推荐答案

@RequestParam 中的数组用于绑定多个同名参数:

Arrays in @RequestParam are used for binding several parameters of the same name:

myparam=myValue1&myparam=myValue2&myparam=myValue3

如果您需要绑定 @ModelAttribute 样式的索引参数,我想您无论如何都需要 @ModelAttribute.

If you need to bind @ModelAttribute-style indexed parameters, I guess you need @ModelAttribute anyway.

这篇关于在@RequestParam 中绑定列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆