我怎样才能通过 thymeleaf 访问 html 文件中的可选值?

How can i get a acces to the optional value in html file by thymeleaf?

由于可选值的访问出现问题

@RequestMapping("fruitDetail/{id}")
public String fruitDetail(@PathVariable("id") int batchId, Model model, Principal principal) {
    if(principal != null) {
        String username = principal.getName();
        User user = userService.findByUsername(username);
        model.addAttribute("user", user);
    }

    Optional<Batch> batch = batchService.findById(batchId);

    model.addAttribute("batch", batch);

    List<Integer> qtyList = Arrays.asList(1,5,10,20,30,40,50,60,70,80,90,100);


    model.addAttribute("qtyList", qtyList);
    model.addAttribute("qty", 1);

    return "fruitDetail";
}

在 html 文件中我得到了这样的东西

<input hidden="hidden" th:field="*{batch.batchId}"/>

Property or field 'batchId' cannot be found on object of type 'java.util.Optional' - maybe not public or not valid?

当我没有像这样的可选值时:{batch.batchId} 正在工作 我怎样才能访问这些值?

您不能这样调用Optional,您可以尝试以下选项:

model.addAttribute("batch", batch.get());

OR

<input hidden="hidden" th:field="*{batch.get().batchId}"/>

您可以在 Java 中模拟如何执行此操作。

例如,如果我在 Java 中有以下选项:

User bob = new User(1, "Bob", 0, "");
Optional<User> user1 = Optional.of(bob);
Optional<User> user2 = Optional.empty();

然后我将在 Java 中访问它们,如下所示:

if (user1.isEmpty()) {
    System.out.println("none");
} else {
    System.out.println(user1.get().getUserName());
}

因此,Thymeleaf 中的等价物是这样的,使用 conditional expression 来实现紧凑性:

<div th:text="${user1.isEmpty()} ? 'none' : ${user1.get().userName}"></div>
<div th:text="${user2.isEmpty()} ? 'none' : ${user2.get().userName}"></div>

这适用于每种情况 - 空可选和非空可选。