繁体   English   中英

如何通过 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}"/>

在“java.util.Optional”类型的 object 上找不到属性或字段“batchId” - 可能不是公共的或无效的?

当我没有像这样的可选值时:{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 中的等价物将是这样的,使用条件表达式来实现紧凑性:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM