Ajax pass a “Map” object to Spring MVC Controller

我的梦境 提交于 2021-02-19 01:47:30

问题


It seems like Spring MVC doesn't know how to map a javascript "map" to a Java map object

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>

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
}

And in the controller,

@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]

I guess there is a way to tell Spring how to map that JSON format string a Java Map?

Thanks!


回答1:


Modify javascript codes:

$.ajax({
     type : "POST",
     url :  "/myURL",
     contentType: "application/json",
     data : JSON.stringify(myMap) // .....

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



回答2:


I have passed the Map object to Java using below code :

Javascript Code :

var values = {
                    "object1" : JSON.stringify(object1),
                    "object2" : JSON.stringify(object2)
            };
 var response = $http.post(url,data);

Server Side Code :

@RequestMapping(value = "/deleteData",method = RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Result deleteData(@RequestBody HashMap<String, Object> dataHashMap) {
    Object1 object1=  (Object1) JsonConvertor.jsonToObject((String) dataHashMap.get("object1"), Object1.class);
        Object2 object2= (Object2) JsonConvertor.jsonToObject((String) dataHashMap.get("object2"), Object2.class);   
}


来源:https://stackoverflow.com/questions/18243462/ajax-pass-a-map-object-to-spring-mvc-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!