java spring thymeleaf:将具有 enum-list-attribute 属性的对象绑定到 html 表单

java spring thymeleaf: bind object with enum-list-attribute attribute to html form

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

//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;
    }
}

现在我想将带有 thymeleaf 的对象绑定到 html 形式,以便轻松地 create/edit 这样的实体。

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