【问题标题】:How can I use a nullable Boolean in combination with Spring Boot and Thymeleaf如何将可空布尔值与 Spring Boot 和 Thymeleaf 结合使用
【发布时间】:2021-02-09 11:13:38
【问题描述】:

我正在尝试在 Thymeleaf 中使用 可为空的布尔值。如果我使用普通的布尔值(原始类型),一切正常。但是当我使用 Boolean 类 时,会出现以下错误:

SmokingAllowed 不可读或具有无效的 getter 方法:是否 getter 的返回类型是否与 setter 的参数类型匹配?

下面的代码应该让您清楚地了解我想要实现的目标。

RoomFilter(Spring 类)

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 (Thymeleaf)

<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>

【问题讨论】:

    标签: spring spring-boot thymeleaf


    【解决方案1】:

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

    Thymeleaf 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>
    

    【讨论】:

    • 这在 Java Bean 规范 (download.oracle.com/otndocs/jcp/…) 中都有解释。并且与 Spring 或 Thymeleaf 无关,而是与 Java 中 bean 自省的工作方式有关。
    猜你喜欢
    • 2021-11-12
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-17
    • 1970-01-01
    • 2017-02-01
    相关资源
    最近更新 更多