简体   繁体   English

如何通过 thymeleaf 访问 html 文件中的可选值?

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

Got a problem with a access becouse of optional value由于可选值,访问出现问题

@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";
}

and in html file i got something like this在 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?在“java.util.Optional”类型的 object 上找不到属性或字段“batchId” - 可能不是公共的或无效的?

when i dont have optional value something like this: {batch.batchId} is working how can i get a access to this values?当我没有像这样的可选值时:{batch.batchId} 正在工作我如何才能访问这些值?

You cannot call Optional this way, you can try the following options:你不能通过这种方式调用Optional ,你可以尝试以下选项:

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

OR

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

You can emulate how you would do this in Java.您可以在 Java 中模拟如何执行此操作。

For example, if I have the following optionals in Java:例如,如果我在 Java 中有以下选项:

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

then I would access them in Java as follows:然后我将在 Java 中访问它们,如下所示:

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

So, the equivalent in Thymeleaf would be this, using a conditional expression for compactness:因此,Thymeleaf 中的等价物将是这样的,使用条件表达式来实现紧凑性:

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

This works for each case - an empty optional and a non-empty optional.这适用于每种情况 - 一个空的可选和一个非空的可选。

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

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