javascript - 如何在 spring boot 中将映射从本地存储传递到 Controller ?

标签 javascript java spring spring-boot

我正在尝试使用 map 将复选框值保存在本地存储中。这样我就可以使用 map 过滤结果。我能够使用 javascript 在本地存储中存储 map 键值。但后来当我从本地存储中检索 map 并将其传递给 Controller ​​时,我得到了带有空值的 map 。

这是我的代码

在本地存储中存储 map

$(':checkbox[name=brand]').on('change', function() {
    var assignedTo = $(':checkbox[name=brand]:checked').map(function() {
        return this.id;
    }).get();
    localStorage.setItem('brands', JSON.stringify(assignedTo))
});

本地存储

enter image description here

传递给 Controller ​​

$.ajax({
    type : "POST",
    url : "filter",
    data : {
        txtMaxAge : localStorage.getItem('txtMaxAge'),
        brands : JSON.parse(localStorage.getItem("brands"))

    }, // parameters
    success : function(result) {
        // alert('changed');
        }
});

Controller

@RequestMapping("/filter")
@ResponseBody
public String filter(
        @RequestParam(value = "txtMaxAge", required = false) String txtMaxAge,
        @RequestParam(value = "brands", required = false) Map<String, String> brands,
        HttpServletRequest request, HttpServletResponse response) {

    System.out.println("max"+txtMaxAge);

    System.out.println("printing map----");

         for (Map.Entry<String,String> entry : brands.entrySet())  
            System.out.println("Key = " + entry.getKey() + 
                             ", Value = " + entry.getValue()); 
    return "send data";
}

我收到这个错误

max10000000
printing map----
2018-12-15 13:37:59.142  WARN 13672 --- [nio-8080-exec-1] .m.m.a.ExceptionHandlerExceptionResolver :
Resolved [java.lang.NullPointerException] to ModelAndView: reference to view with name 'error';
model is {errorTitle=Contact Your Administrator!!, errorDescription=java.lang.NullPointerException

我做错了什么?

最佳答案

问题是品牌不是 map 类型,它是一个字符串数组。相应地更改类型,它应该可以工作。

关于javascript - 如何在 spring boot 中将映射从本地存储传递到 Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53790752/

相关文章:

javascript - 第一个单击处理程序删除元素,第二个处理程序不运行,我如何运行两者?

javascript - 使用 lodash 合并具有不同键的 2 个对象数组

java - 快速排序算法无法正常工作

java - @EnableAspectJAutoProxy 不起作用

java - 为什么 Spring 注释 Controller 优于传统映射?

java - Spring Cloud Kubernetes 重新加载时序问题

javascript - 动态添加字段输入不存储值并传递给 Controller

javascript - 验证空白字符串

java - 在 WebLogic Server v10.3 中注入(inject) EJB 3.0

java - 如何使用 Spring MockMVC 将 JSON 编码为请求参数