spring - 如何将可空布尔值与 Spring Boot 和 Thymeleaf 结合使用
问题描述
我正在尝试在Thymeleaf
. 如果我使用普通的布尔值(原始类型),一切正常。但是当我使用布尔类时,出现以下错误:
SmokeAllowed 不可读或有无效的 getter 方法:getter 的返回类型是否与 setter 的参数类型匹配?
下面的代码应该让您清楚地了解我想要实现的目标。
RoomFilter(弹簧类)
public class RoomFilter {
private RoomType roomType;
private Boolean smokingAllowed;
public RoomType getRoomType() {
return roomType;
}
public void setRoomType(RoomType roomType) {
this.roomType = roomType;
}
public Boolean isSmokingAllowed() {
return smokingAllowed;
}
public void setSmokingAllowed(Boolean smokingAllowed) {
this.smokingAllowed = smokingAllowed;
}
}
HTML(百里香叶)
<select class="form-control" th:field="*{smokingAllowed}">
<option th:value="null" selected>---</option>
<option th:value="1">Smoking allowed</option>
<option th:value="0">Smoking not allowed</option>
</select>
解决方案
我找到了解决方案。由于默认情况下 Boolean 类不被识别为布尔值,因此您需要有不同的命名约定。
当您使用布尔值(原始类型)时,Thymeleaf / Spring 正在寻找名为 isNameOfProperty() 的 getter。
当您使用布尔(类)Thymeleaf / Spring 正在寻找名为 getNameOfProperty() 的 getter 时。
因此,以下代码有效:
春天
public class RoomFilter {
private RoomType roomType;
private Boolean smokingAllowed;
public RoomType getRoomType() {
return roomType;
}
public void setRoomType(RoomType roomType) {
this.roomType = roomType;
}
public Boolean getSmokingAllowed() {
return smokingAllowed;
}
public void setSmokingAllowed(Boolean smokingAllowed) {
this.smokingAllowed = smokingAllowed;
}
}
百里香 HTML
<select class="form-control" th:field="*{smokingAllowed}" onchange="this.form.submit()">
<option th:value="null" selected>---</option>
<option th:value="true">Smoking allowed</option>
<option th:value="false">Smoking not allowed</option>
</select>
推荐阅读
- python - 如何从 DataFrame 中选择特定值?
- internet-explorer-11 - Microsoft Edge 是否支持在 IE8 模式下呈现?有什么解决办法吗?
- python - 如何解决这个 ValueError: Dimension 1 in both shape must be equal 问题?
- css - 我们如何使用样式化组件进行集中化?
- r - 在 dplyr 的 mutate 中使用带有 .data[[]] 的变量
- java - 泛型类名称与泛型参数相同
- flutter - 更新文本小部件 onTap
- java - 我可以在这个类中使用 java 类的访问器方法(getter 和 setter)吗?
- sed - 如何使用“sed”命令替换字符串的尾部
- xamarin - 是否可以跳过登录页面来运行 Xamarin UI 测试?