如何将可空布尔值与spring boot和thymeleaf结合使用

vybvopom  于 2021-07-23  发布在  Java
关注(0)|答案(1)|浏览(368)

我想用一个可为空的布尔值 Thymeleaf . 如果我使用一个普通的布尔型(基元类型),一切正常。但是当我使用布尔类时,我得到以下错误:
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(英文)

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

pbpqsu0x1#

我找到了解决办法。由于默认情况下布尔类不会被识别为布尔类,因此需要有不同的命名约定。
当您使用布尔(基本类型)时,thymeleaf/spring正在查找名为isnameofproperty()的getter。
当您使用布尔(类)时,thymeleaf/spring正在查找名为getnameofproperty()的getter。
因此,以下代码起作用:
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 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>

相关问题