我網站上的當前輸出...
這是 --- Optional[User(id=111, username=Juan Lopez, password=Juanini123, post=Hoy es un gran dia)] 的個人頁面
所需的輸出只是顯示名稱“Juan Lopez”
我的 HTML (Thymleaf)...
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Personal Profile</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<div class="positionlist" th:unless="${#lists.isEmpty(personalUser)}">
<span>This is the personal page of --- </span>
<span th:text="${personalUser}"></span>
</div>
</body>
</html>
我的控制器(Spring Boot):
package com.littlesocial.sm;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.ui.Model;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
@Controller
public class UserController {
@NonNull
private final UserRepository userRepository;
@GetMapping("/myProfile")
public String getPersonalUserProfile(Model model){
userRepository.save(
new User(111L,"Juan Lopez", "Juanini123", "Hoy es un gran dia"));
model.addAttribute("personalUser", userRepository.findById(111L));
return "personalUserProfile";
}
}
我嘗試過諸如personalUser.username之類的東西 - 但它不起作用。
uj5u.com熱心網友回復:
請做到:
<span th:text="${personalUser.get().username}"></span>
或者:
Optional<User> foundInDb = userRepository.findById(111L);
if (foundInDb.present()) {
model.addAttribute("personalUserName", // e.g.
foundInDb.get().getUserName()
);
}
根據:
th:text="personalUserName"
有很多 Thx 到:如何通過 thymeleaf 訪問 html 檔案中的可選值?
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/390083.html
上一篇:如何在Java投影中設定變數?
