spring - 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);
}
解决方案
您可以通过引入以下内容使当前用户可用于 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;
}
}
推荐阅读
- python - Selenium - 无法在动态元素中获取 xpath
- ansible - 如何使用 ANSIBLE 将多个主机的多个 stdout_lines 保存到一个 txt 文件?
- facebook - 如何在后端验证 Facebook 用户访问令牌?
- java - 考虑在你的配置中定义一个 'org.springframework.data.mongodb.core.MongoTemplate' 类型的 bean
- flask - flask_restful:无法执行 POST 操作 > 错误代码:500 内部服务器错误
- flutter - 流订阅不监听flutter的变化
- node.js - Windows7/32 位。关闭后无法运行 MongoDB。我必须删除 db 目录中的所有文件。然后它工作。但是我丢失了所有上一个文件
- java - 如何旋转 HSSFShapeTypes.ThickArrow
- javascript - 查询每个快照不是一个函数
- java - 向 http 服务器发送了许多异步请求,但一次只处理几个请求