首页 > 解决方案 > 如何将可空布尔值与 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>

标签: springspring-bootthymeleaf

解决方案


我找到了解决方案。由于默认情况下 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>

推荐阅读