java - Spring 启动[Thymeleaf] : EL1008E: Property or field 'category' cannot be found on object of type 'java.util.Optional'

标签 java spring-boot thymeleaf

我在两个表产品产品类别之间有关系。现在我想编辑产品。

我创建了一个列表,当我单击“编辑”时,打开另一个界面,其中包含产品详细信息和产品类别作为下拉列表,但我在 thymeleaf th:selected 上收到错误,因为我希望它显示包含所选项目的下拉列表在其中,但我收到错误

EL1008E:在“java.util.Optional”类型的对象上找不到属性或字段“类别”

请帮忙解决

我尝试更改选择以输入它工作正常

<input type="text" class="form-control" id="name" name="name" th:field="<b>${update.category.ProductCategoryID}"</b> />

但是使用选定的不起作用

<select class="form-control" id="category" name="category">
    <option 
        th:each="prodCat : ${prodCatList}" 
        th:value="${prodCat.ProductCategoryID}" 
        th:text="${prodCat.CategoryName}"                            
        th:selected="${prodCat.ProductCategoryID} =={update.category.ProductCategoryID}">
    </option>
</select>

下面是代码片段

<form th:object="${update}" th:action="@{/product/save}" method="post">
  <div id="myForm">
....
<input type="text" class="form-control" id="name" name="name" th:field="${update.category.ProductCategoryID}" /> 
<select class="form-control" id="category" name="category">
    <option 
        th:each="prodCat : ${prodCatList}" 
        th:value="${prodCat.ProductCategoryID}" 
        th:text="${prodCat.CategoryName}"
        th:selected="${prodCat.ProductCategoryID} == ${update.category.ProductCategoryID}" <-- problem
        >
    </option>
</select>
<input type="text" class="form-control" id="ProdID" name="ProdID" th:field="${update.category.CategoryName}" />

最佳答案

看来Update是Optional而不是对象,并且 View 接收的是Optional而不是直接Update。

//something like this needs to be done when updating the model for this attribute
Optional<Update> update = <your code to get this in Java>
update.ifPresent(foundUpdateObject -> model.addAttribute("update", foundUpdateObject))

关于java - Spring 启动[Thymeleaf] : EL1008E: Property or field 'category' cannot be found on object of type 'java.util.Optional' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56522629/

相关文章:

java - 使用哪一个 : Java Swing or GTK+ for GNOME desktop application?

java - 当组件已经测试时测试复合对象 ->冗余?

java - 将 Spring Boot 应用程序部署到 heroku - 错误消息 "No web processes running"

java - 我在哪里可以获得 Spring Boot 默认记录器格式?

java - 已解决 [org.springframework.web.HttpRequestMethodNotSupportedException : Request method 'POST' not supported]

java - 安卓 - java.lang.UnsatisfiedLinkError : Native method not found

java - Android服务未绑定(bind)

java - 按钮无法正常工作 - Java Spring Thymeleaf

java - Springboot 1.5.1迁移到2.0.1实例格式

java - 无法到达链接 th :src route on thymeleaf