简体   繁体   中英

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

<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?

when i dont have optional value something like this: {batch.batchId} is working how can i get a access to this values?

You cannot call Optional this way, you can try the following options:

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

OR

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

You can emulate how you would do this in Java.

For example, if I have the following optionals in 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:

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:

<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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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