Spring + jQuery + FTL:如何处理 "on" 或 null 的复选框值

Spring + jQuery + FTL: how to handle checkbox value of "on" or null

当我序列化我的表单并使用一些代码将序列化的查询字符串转换为 JSON 对象时,我插入的复选框:

<@spring.formCheckbox path="signUpDto.checkbox_terms" />

的 "checked" 和 "unchecked" 值分别为 "on" 和 null。我用谷歌搜索了这种行为,发现这是 jQuery 表单序列化的标准行为。

在我的 DTO 中,我的 checkbox_terms 变量声明如下:

private boolean checkbox_terms;

但是,当我尝试 post 我的序列化对象表单数据返回服务器时,它 returns 出现 400 错误(错误请求)。可能是因为 checkbox_terms 上的数据类型错误,因为这两个值是 "on" 和 null。

所以我的问题是,我应该如何处理这种情况?

为什么您认为问题出在复选框上? 因为 415 错误意味着 POST 请求的 Content-Type 没有被服务器处理,在这种情况下是 application/json.

我猜你使用 Spring MVC。那么您可以尝试在 RequestMapping.

中设置 consumes="application/json"

参考文献:https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestMapping.html#consumes--

只需将 boolean 更改为字符串,如下所示:

private String checkbox_terms;

当你需要检查它是否被选中时,做

[dto].getCheckbox_terms().equalsIgnoreCase("on")

选中或

![dto].getCheckbox_terms().equalsIgnoreCase("on")

未选中。