Home > Software design >  How can I access a property of my object Thymeleaf (Spring Boot)
How can I access a property of my object Thymeleaf (Spring Boot)

Time:12-21

Current output on my website...

This is the personal page of --- Optional[User(id=111, username=Juan Lopez, password=Juanini123, post=Hoy es un gran dia)]

Desired output would be just to show the name, "Juan Lopez"

My 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  th:unless="${#lists.isEmpty(personalUser)}">

        <span>This is the personal page of --- </span>
        <span th:text="${personalUser}"></span>

    </div>

</body>
</html>

My controller (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";
    }


}

I have tried stuff like personalUser.username - but it does not work.

CodePudding user response:

Please make it:

<span th:text="${personalUser.get().username}"></span>

Or:

Optional<User> foundInDb = userRepository.findById(111L);
if (foundInDb.present()) {
  model.addAttribute("personalUserName", // e.g.
     foundInDb.get().getUserName()
  );
}

with the according:

th:text="personalUserName"

With many Thx to: How can i get a acces to the optional value in html file by thymeleaf?

  • Related