spring - Thymeleaf 获取当前登录的用户名作为字符串

标签 spring spring-boot spring-mvc spring-security thymeleaf

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

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

这是我在 Controller 层的GetMapping

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

最佳答案

您可以通过引入 @ControllerAdvice 让当前用户对 Thymeleaf 模型可用:

@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;
    }
}

关于spring - Thymeleaf 获取当前登录的用户名作为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65009999/

相关文章:

java - Spring Roo 命令执行包错误

java - 如何使用 spring Security 根据邮件和 uid 从 LDAP 验证用户?

java - 如何保护 Spring Data REST 关联请求的安全?

java - 使用 Spring Cache 缓存嵌套对象?

spring - Spring Boot如何在不重新启动服务器的情况下加载代码中的更改

java - Spring:客户端发送的请求语法错误()

javascript - Ajax在jsp中进行id检查仅返回相同的结果

Spring MVC如何获得运行异步任务的进度

spring - Spring Security Core-自定义错误重定向网址

javascript - 在没有表单的情况下从ajax向spring Controller 发送多部分请求?