我有一个Java脚本地图,其中包含我需要发送到spring boot控制器的键值对: -
示例: -
var myMap = new Map();
myMap.set('1', 'value1');
myMap.set('2', 'value2');

我无法在Spring启动控制器中获取此JavaScript(js)地图。 根据我的最佳实践,我试图在Java的HashMap或Map中获取此地图。 非常感谢帮助。 :)
答案 0 :(得分:1)
尝试以下:
var myMap = {};
myMap["names"] = ["Alex"];
myMap["fruit"] = ["Apple"];
修改javascript代码以使用Ajax:
$.ajax({
type : "POST",
url : "/reqURL",
contentType: "application/json",
data : JSON.stringify(myMap) // .....
控制器代码如下:
@RequestMapping(value = "/reqURL", method = RequestMethod.POST, consumes="application/json")
@ResponseBody
public List<String> reqControl(@RequestBody Map<String, List<String>> myMap) {
// do something with parameters ...
}
答案 1 :(得分:0)
var myMap = new Map();
myMap.set('1', 'value1');
myMap.set('2', 'value2');
myMap.set('3', 'value3');
myMap.set('4', 'value4');
//Making JS Map compatible for JSON.Stringify
const out = Object.create(null)
myMap.forEach((value, key) => {
if (value instanceof Map) {
out[key] = map_to_object(value)
}
else {
out[key] = value
}
})
$.ajax({
type : "POST",
url : "/yourURL",
contentType: "application/json",
data : JSON.stringify(myMap) //......
@RequestMapping(value = "/yourURL", method = RequestMethod.POST, consumes="application/json")
@ResponseBody
public List<String> reqControl(@RequestBody Map<String,<String> myMap) {
// further code.
}