春季启动[Thymeleaf]:EL1008E:在类型为'java.util.Optional'的对象上找不到属性或字段'category'

时间:2019-06-10 08:00:12

标签: java spring-boot thymeleaf

我在两个表 product product category 之间存在关系。现在我要编辑产品。

我创建了一个列表,单击编辑后会打开另一个界面,其中包含产品详细信息以及产品类别作为下拉菜单,但是我在thymeleaf th:selected上遇到错误,因为我希望它显示包含所选项目的下拉菜单在其中,但出现错误

EL1008E:在类型为'java.util.Optional'的对象上找不到属性或字段'category'

请帮助解决

我试图将选择更改为输入,效果很好

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

2 个答案:

答案 0 :(得分:1)

感谢TechFree。

工作正常,我在没有从可选类中获取对象时犯了一个错误

这是我输入的代码,它可以正常工作。

@GetMapping("/edit/{pctid}")
public String findOne(
            @PathVariable(value = "pctid") Integer pctid,
        Model model) {
    model.addAttribute("prodCatList", productCategoryRepo.findAll());

   productRepo.findById(pctid).ifPresent(o -> model.addAttribute("update", o));
//      model.addAttribute("update",productRepo.findById(pctid));
        return "/prod/edit";

    }

答案 1 :(得分:0)

似乎Update是可选的,而不是对象,并且视图收到的是Öptional而不是直接更新。

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