【问题标题】:How can I access a property of my object Thymeleaf (Spring Boot)如何访问我的对象 Thymeleaf 的属性(Spring Boot)
【发布时间】:2022-01-22 13:35:40
【问题描述】:

我网站上的当前输出...

这是 --- 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";
    }


}

我尝试过诸如个人用户.用户名之类的东西 - 但它不起作用。

【问题讨论】:

  • th:unless="${#lists.isEmpty(personalUser)} 可能是问题!(?)尝试/更好:th:unless="${personalUser}。绝对问题:两次调用您的控制器..(id:111L)..希望“Juanini123”不是真正的密码:))
  • @xerx593 这不是问题,它实际上只是不允许我访问 Optional 类中输出“Optional[User(id=111, username=Juan Lopez, password=Juanini123 , post=Hoy es un gran dia)]" 是的,那是我的密码!开玩笑哈哈
  • 现在,得到你! look here(接受的答案:2 个备选方案),现在您必须始终如一地申请 ${personalUser.get().username}(或您要显示的内容)
  • @xerx593 是的!它起作用了……我快要高兴得哭了。谢谢!!!!!想回答这个问题让我批准吗?还是我应该这样做?还是我们应该复制它?
  • 我分享你的快乐!谢谢你,非常欢迎! :-)

标签: spring spring-boot thymeleaf


【解决方案1】:

请做:

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

感谢很多人:How can i get a acces to the optional value in html file by thymeleaf?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-15
    • 2016-07-13
    • 2016-07-12
    • 2019-10-19
    • 1970-01-01
    相关资源
    最近更新 更多