[英]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.