how to capture multiple parameters using @RequestParam using spring mvc?
假设单击了超链接,并使用以下参数列表
我的要求是我必须捕获所有参数并将它们放在地图中。
请帮忙!
1 2 3 4 5 6 7 8 9 | @RequestMapping(value ="users/newuser", method = RequestMethod.POST) public String saveUser(@RequestParam Map<String,String> requestParams) throws Exception{ String userName=requestParams.get("email"); String password=requestParams.get("password"); //perform DB operations return"profile"; } |
您可以按上述方式使用RequestParam。
看来你听不懂
1 | Map<String,String> |
因为您所有的参数都具有相同的名称" myparam"
尝试以下方法:
1 | public ModelAndView method(@RequestParam("myparam") List<String> params) { } |
要一次获取所有参数,请尝试以下操作:
1 | public ModelAndView postResultPage(@RequestParam MultiValueMap<String, String> params) |
Annotation which indicates that a method parameter should be bound to a web request parameter. Supported for annotated handler methods in Servlet and Portlet environments.
If the method parameter type is Map and a request parameter name is specified, then the request parameter value is converted to a Map assuming an appropriate conversion strategy is available.
If the method parameter is
Map orMultiValueMap and a parameter name is not specified, then the map parameter is populated with all request parameter names and values.
从Spring 3.0开始,您还可以使用MultiValueMap实现此目的:
一个简单的例子是:
1 2 3 4 5 6 7 8 9 10 11 12 | public String someMethod(@RequestParam MultiValueMap<String,String> params) { final Iterator<Entry<String, List<String>>> it = params.entrySet().iterator(); while(it.hasNext()) { final String k = it.next().getKey(); final List<String> values = it.next().getValue(); } return"dummy_response"; } |
如果有人尝试在Spring Boot中执行相同的操作,请使用
Spring mvc可以支持
如果您的对象是
1 2 3 4 5 6 | public class User { private String name; private int age; // getter and setter } |
而且您想要传递
1 | http://127.0.0.1:8080/list?users[0].name=Alice&users[0].age=26&users[1].name=Bob&users[1].age=16 |
记住要对URL进行编码,编码后的URL是这样的:
1 | http://127.0.0.1:8080/list?users%5B0%5D.name=Alice&users%5B0%5D.age=26&users%5B1%5D.name=Bob&users%5B1%5D.age=16 |