I have a complicated html form that dynamically created with java script.
I want to get the map of key-value pairs as a Map in java and store them.
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?
While working with Servlets, when we want to fetch the form data; we used the object of HttpServletRequest to get the data from the form and used the getParameter() method. Unlike this, Spring MVC provides us the annotation to extract form data i.e @RequestParam Annotation.
In Spring MVC, the @RequestParam annotation is used to read the form data and bind it automatically to the parameter present in the provided method.
You can also use @RequestBody
with MultiValueMap
e.g.
@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.
MultiValueMap is in Spring utils package
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With