首页 > 解决方案 > Thymeleaf 获取当前登录的用户名作为字符串

问题描述

我是 Thymeleaf 的新手,目前正在使用 Springboot 开发用户管理工具。首先需要登录帐户才能查看个人数据。我的问题是,要获取当前登录的用户名,在我的情况下这是一封电子邮件,并使用 Getmapping 调用带有 URL“/{email}”的 Rest-API?

我的想法是获取 securitycontextholder.getcontext().getprincipal() 并将其传递给 Request call 。最后显示数据

这是我从控制器层获取映射

 @GetMapping("/{email}")
public ResponseEntity getApplicantByEmail(@PathVariable String email){
    return new ResponseEntity(applicantService.getApplicantByEmail(email), HttpStatus.OK);
}

标签: springspring-bootspring-mvcspring-securitythymeleaf

解决方案


您可以通过引入以下内容使当前用户可用于 Thymeleaf 模型@ControllerAdvice

@ControllerAdvice
public class CurrentUserAdvice {
    @ModelAttribute("currentEmailAddress")
    public String emailAddress(Authentication authentication) {
        return authentication.getName();
    }
}

这将使模型属性currentEmailAddress在 Thymeleaf 模板中可用。

如果您有一个自定义域对象作为 中的主体Authentication,则可以使用相同的模式使整个用户在模型中可用:

@ControllerAdvice
public class CurrentUserAdvice {
    @ModelAttribute("currentUser")
    public MyUser user(@AuthenticationPrincipal MyUser user) {
        return user;
    }
}

推荐阅读