Java 如何在 Spring MVC 控制器中将表单数据作为地图获取?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24551915/
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
How to get Form data as a Map in Spring MVC controller?
提问by Morteza Adi
I have a complicated html form that dynamically created with java script.
我有一个复杂的 html 表单,它是用 java 脚本动态创建的。
I want to get the map of key-value pairs as a Map in java and store them.
我想在java中将键值对的映射作为映射获取并存储它们。
here is my controller to get the submitted data.
这是我的控制器来获取提交的数据。
@RequestMapping(value="/create", method=RequestMethod.POST,
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public String createRole(Hashmap<String, Object) keyVals) {
....
}
but my map is empty.
但我的地图是空的。
How can i get form data as a map of name-value pairs in Spring mvc controller?
如何在 Spring mvc 控制器中获取表单数据作为名称-值对的映射?
采纳答案by optional
You can also use @RequestBody
with MultiValueMap
e.g.
您也可以@RequestBody
与MultiValueMap
例如一起使用
@RequestMapping(value="/create",
method=RequestMethod.POST,
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public String createRole(@RequestBody MultiValueMap<String, String> formData){
// your code goes here
}
Now you can get parameter names and their values.
现在您可以获取参数名称及其值。
MultiValueMapis in Spring utils package
MultiValueMap位于 Spring utils 包中
回答by Morteza Adi
I,ve just found a solution
我刚刚找到了解决方案
@RequestMapping(value="/create", method=RequestMethod.POST,
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public String createRole(HttpServletRequest request) {
Map<String, String[]> parameterMap = request.getParameterMap();
...
}
this way i have a map of submitted parameters.
这样我就有了一张提交参数的地图。
回答by Dulith De Costa
Try this,
尝试这个,
@RequestMapping(value = "/create", method = RequestMethod.POST,
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public String createRole(@RequestParam HashMap<String, String> formData) {
回答by Cranberry
The answers above already correctly point out that @RequestParam annotation is missing. Just to add why thta is required,
上面的答案已经正确指出缺少 @RequestParam 注释。只是为了补充为什么需要thta,
A simple GET request would be soemthing like :
一个简单的 GET 请求类似于:
http://localhost:8080/api/foos?id=abc
In controller, we need to map the function paramter to the parameter in the GET request. So we write the controller as
在控制器中,我们需要将函数参数映射到 GET 请求中的参数。所以我们把控制器写成
@GetMapping("/api/foos")
@ResponseBody
public String getFoos(@RequestParam String id) {
return "ID: " + id;
}
and add @RequestParam for the mapping of the paramter "id".
并为参数“id”的映射添加@RequestParam。