How can I display the current logged in User with Spring Boot Thymeleaf?

后端 未结 4 683
故里飘歌
故里飘歌 2021-01-18 19:18

I am trying to display the details of the current user however I keep getting errors. I tried accessing the authenticated user from the template but that did not work as I w

4条回答
  •  轮回少年
    2021-01-18 19:37

    I figured out how to fix my problem.

    I created this method in a controller:

      @Autowired
    UserRepository userR;
    @GetMapping
    public String currentUser(@ModelAttribute("user") @Valid UserRegistrationDto userDto, BindingResult result, Model model) {
    
        Authentication loggedInUser = SecurityContextHolder.getContext().getAuthentication();
        String email = loggedInUser.getName(); 
    
         User user = userR.findByEmailAddress(email);
        String firstname = user.getFirstName();
         model.addAttribute("firstName", firstname);
        model.addAttribute("emailAddress", email);
    
        return "userProfile1"; //this is the name of my template
    }
    

    and then I added this line of code in my html template:

    Email: th:text="${emailAddress}"

提交回复
热议问题