我是 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/