Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
777 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...