本文介绍了Ajax通过“地图" Spring MVC Controller的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Spring MVC似乎不知道如何将javascript"map"映射到Java map对象
It seems like Spring MVC doesn't know how to map a javascript "map" to a Java map object
在网络用户界面中,例如foo.jsp
In the web UI, say, foo.jsp,
<script>
var myMap = {};
myMap["people"] = ["Alex","Bob","Charles","Dave"];
myMap["fruit"] = ["Apple","Orange"];
$.ajax({
type : "POST",
url : "/myURL",
data : "myMap=" + myMap, // I tried "myMap="+JSON.stringify(myMap), as well, it doesn't work neither
success : function(response) {
alert("Success! response = " + response);
},
error : function(e) {
alert("AJAX error");
}
});
</script>
在服务器端,我有一个数据模型类,仅用于从Web UI接收数据
On the server side, I have a data model class just to receive data from the Web UI
@Setter @Getter
class Parameters {
private Map<String, List<String>> myMap; //this is the java class I want to map the string to
}
在控制器中,
@RequestMapping(value = "/myURL", method = RequestMethod.POST)
@ResponseBody
public List<String> fooControl(Parameters parameters ) {
// do something with parameters ...
}
我在服务器端遇到的错误是,
The error I got on the server side is like,
[tomcat:launch] Aug 14, 2013 3:12:37 PM org.apache.catalina.core.StandardWrapperValve invoke
[tomcat:launch] SEVERE: Servlet.service() for servlet dispatcher threw exception
[tomcat:launch] org.springframework.validation.BindException:
org.springframework.validation.BeanPropertyBindingResult: 1 errors
[tomcat:launch] Field error in object 'Parameters ' on field
'myMap': rejected value [{"people":["Alex","Bob","Charles","Dave"],"fruit":
["Apple","Orange"]}]; codes
[typeMismatch.repairInfomationParametersExperimental.constraints,typeMismatch.constraints,typeMismatch.java.util.Map,typeMismatch]; arguments
[org.springframework.context.support.DefaultMessageSourceResolvable: codes
[repairInfomationParametersExperimental.constraints,constraints]; arguments []; default message
[constraints]]; default message [Failed to convert property value of type 'java.lang.String' to
required type 'java.util.Map' for property 'constraints'; nested exception is
java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type
[java.util.Map] for property 'myMap': no matching editors or conversion strategy found]
我想有一种方法可以告诉Spring如何将JSON格式的字符串映射为Java Map?
I guess there is a way to tell Spring how to map that JSON format string a Java Map?
谢谢!
推荐答案
修改javascript代码:
Modify javascript codes:
$.ajax({
type : "POST",
url : "/myURL",
contentType: "application/json",
data : JSON.stringify(myMap) // .....
修改服务器端Java代码:
Modify server side java codes:
@RequestMapping(value = "/myURL", method = RequestMethod.POST, consumes="application/json")
@ResponseBody
public List<String> fooControl(@RequestBody Map<String, List<String>> myMap) {
// do something with parameters ...
}
这篇关于Ajax通过“地图" Spring MVC Controller的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!