一尘不染

如何将javascript(js)映射传递给Spring Boot Controller?

spring-boot

我有一个Java Script映射,其中包含需要发送给Spring Boot Contoller的键值对:-

示例:-

 var myMap = new Map();

     myMap.set('1', 'value1');

     myMap.set('2', 'value2');

我无法在Spring
Boot控制器中获取此JavaScript(js)映射。按照我的最佳实践,我试图在Java的HashMap或Map中获取此地图。非常感谢您的帮助。:)


阅读 555

收藏
2020-05-30

共1个答案

一尘不染

我想出了解决方案:-

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.   
    }
2020-05-30