我正在尝试使用 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))
});
本地存储
传递给 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/