Thymeleaf 在对象上的列表中多选

Zur*_*uri 5 java select list spring-mvc thymeleaf

Thymeleaf 在对象上的列表中多选

我正在使用 Thymeleaf 和 Spring MVC,我想做这样的多重选择:

<form action="#" th:object="${promotion}" th:action="@{/promotion/add}" method="post">

<select th:field="*{products.id}" th:value="*{products.id}"  multiple="multiple" >
  <optgroup th:each="c : ${categories}" th:label="${c.name}">   
     <option th:each="p : ${c.products}" th:value="${p.id}" th:text="${p.name}" />
  </optgroup>
</select>
</form>
Run Code Online (Sandbox Code Playgroud)

我有这个对象的形式

public class Promotion implements Serializable{
    private static final long serialVersionUID = 1L;
    private int id;
    private String name;
    private List<PromoProduct> products;
}

public class PromoProduct implements Serializable {
    private static final long serialVersionUID = 1L;
    private int id;
    private List<Integer> products;
    private int amount;
}
Run Code Online (Sandbox Code Playgroud)

使用此代码,我收到以下错误消息:

org.springframework.web.util.NestedServletException: Request processing failed;
    nested exception is org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "products.id" .
Run Code Online (Sandbox Code Playgroud)

我想获取 id 变量(产品列表内)的选定数据。我可以这样做吗?我不知道这是否可能,如果它是如何到达产品对象内的 id 变量?

san*_*uck 1

不久 -products是的List,所以它没有字段id。您需要创建PropertyEditor来实现您想要的行为。
@tom-verelst 在thymeleaf 中在编辑时选择了多个,给出了很好的答案。请检查一下。