传递一个地图<字符串,字符串>到控制器用SpringMVC [英] Passing a Map<String,String> to a springMVC controller

查看:135
本文介绍了传递一个地图<字符串,字符串>到控制器用SpringMVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图发送一个HashMap或任何其他Map实现从阿贾克斯到Spring MVC的控制器

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 :

Ajax调用是如下

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 ?

感谢你。

推荐答案

结合在弹簧控制器地图支持相同的方式结合的阵列。无特殊转换需要!

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:

  • 的用途的命令的对象(S)作为顶级值保持。一个命令对象可以是任何类。
  • Spring uses command object(s) as a top level value holder. A command object can be any class.

因此​​,所有你需要的是一个包装类(<$ C C $> TagsWrapper )持有类型的字段地图&LT;字符串,字符串&GT; 所谓的标签。 同样的方法,你需要绑定一个数组。

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.

这是说明pretty的很好的文档,但我仍然会忘记的包装对象,需要过一段时间;)

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:

  • 使用每个地图密钥一种形式的参数,而不是一个完整的字符串重新完整的地图的presentation。
  • 一个输入值应该是这样的:

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

这篇关于传递一个地图&LT;字符串,字符串&GT;到控制器用SpringMVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆