Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Form data as a Map in Spring MVC controller?

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?

like image 575
Morteza Adi Avatar asked Jul 03 '14 10:07

Morteza Adi


People also ask

How we can fetch form data in controller method in Spring MVC?

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.

How can you read only on parameter value from a form in Spring MVC?

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.


2 Answers

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

like image 185
optional Avatar answered Sep 22 '22 13:09

optional


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.

like image 41
Morteza Adi Avatar answered Sep 19 '22 13:09

Morteza Adi