Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a Map<String,String> to a springMVC controller

I am trying to send a HashMap or any other Map implementation from ajax to a Spring MVC controller

Here's the detail of how I do it :

the Ajax call is as follow

var tags = {};
tags["foo"] = "bar";
tags["whee"] = "whizzz";


$.post("doTestMap.do",   {"tags" : tags }, function(data, textStatus, jqXHR) {
if (textStatus == 'success') {
    //handle success
    console.log("doTest returned " + data);
} else {
    console.err("doTest returned " + data);
}
}); 

then on the controller side I have :

@RequestMapping(value="/publisher/doTestMap.do", method=RequestMethod.POST)
public @ResponseBody String doTestMap(@RequestParam(value = "tags", defaultValue = "") HashMap<String,String> tags, HttpServletRequest request) {  //

    System.out.println(tags);

    return "cool";
} 

Unfortunately I systematically get

org.springframework.beans.ConversionNotSupportedException: Failed to convert value of type 'java.lang.String' to required type 'java.util.Map'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.util.Map]: no matching editors or conversion strategy found

What am I doing wrong ?

Thank you.

like image 426
azpublic Avatar asked Aug 16 '13 19:08

azpublic


1 Answers

Binding a map in a spring controller is supported the same way as binding an array. No special converter needed!

There is one thing to keep in mind though:

  • Spring uses command object(s) as a top level value holder. A command object can be any class.

So all you need is a wrapper class (TagsWrapper) which holds a field of type Map<String, String> called tags. The same approach you take to bind an array.

This is explained pretty well in the docs but i kept forgetting the need of the wrapper object once in a while ;)

The second thing you need to change is the way you submit the tags values:

  • use one form parameter per map key and not a full string representation of the complete map.
  • one input value should look like this:

      <input type="text" name="tags[key]" value="something">
    

If tags is a map in a wrapper this works out of the box for form submits.

like image 162
Martin Frey Avatar answered Nov 16 '22 01:11

Martin Frey