Java Spring Thymeleaf:将具有枚举列表属性属性的对象绑定到 HTML 表单



我有一个实体,其中包含可能的运输选项列表:

//ShippingType.java
public enum ShippingType {
    DOWNLOAD,
    SHIPPING
}

//SoftwareType.java
@Entity
public class SoftwareType {
    //...
    @Column(unique = true)
    private String name;
    @ElementCollection(targetClass=ShippingType.class)
    @CollectionTable(name = "softwaretype_shippingtype", joinColumns = @JoinColumn(name = "softwaretype_id"))
    @Column(name = "shippingtype", nullable = false)
    @Enumerated(EnumType.STRING)
    private List<ShippingType> supportedShippingTypes;
    //...
    public List<ShippingType> getSupportedShippingTypes() {
        return supportedShippingTypes;
    }
    public void setSupportedShippingTypes(List<ShippingType> supportedShippingTypes) {
        this.supportedShippingTypes = supportedShippingTypes;
    }
}

现在我想将带有百里香叶的对象绑定到 html 表单上,以便轻松创建/编辑此类实体。

<div class="panel-body" th:fragment="createUpdateForm(action, SoftwareType)">
    <form role="form" action="#" th:action="@{${action}}" th:object="${SoftwareType}" method="post">
        <label for="softwareTypeName">Name</label>
        <input type="text" th:field="*{name}" id="softwareTypeName"/>
        <!-- how to insert checkboxes of shippingTypes ?? -->
        <button type="submit" value="submit"/>
    </form>
</div>

但是,如何插入包含所有 ShippingType 的复选框列表并将其绑定到对象?

你可以

迭代你的枚举ShippingType,例如:

<div th:each="shippingType : ${T(com.example.ShippingType).values()}">
    <input type="checkbox" th:id="${{shippingType}}" th:value="${{shippingType}}" th:field="*{supportedShippingTypes}" />
    <label th:for="${{shippingType}}">Shipping Types</label>
</div>

最新更新