用于登录的凭据是用户名和密码。我想在主页显示名称
<span sec:authentication="name">bob</span>
但它仅提供登录过程中使用的用户名。怎么做。我正在使用 spring mvc。请帮忙
最佳答案
您可以从 Spring Security Context 获取用户并将其转换为您的“用户”模型,然后按照您的喜好对待它。在此示例中,我使用 @ModelAttribute,您可以将其添加到 Controller 或顾问 (@ControllerAdvice) 中
@ModelAttribute("user")
public MyCustomUser getUser() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null && auth.isAuthenticated() && !"anonymousUser".equals(auth.getPrincipal())) {
return (MyCustomUser) auth.getPrincipal();
}
return null;
}
然后在你的html中<span th:text="${user} ? ${user.name} : Bob">Bob</span>
关于java - 需要更改使用的名称 sec :authentication in thymeleaf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34852867/