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.
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:
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:
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.
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