需要更改名称使用sec:在thymeleaf中进行身份验证

时间:2016-01-18 10:50:00

标签: java spring-security thymeleaf

用于登录的凭据是用户名和密码。我想在主页上显示名称

      <span sec:authentication="name">bob</span>

但它只提供登录过程中使用的用户名。怎么做。我正在使用spring mvc。请帮忙

1 个答案:

答案 0 :(得分:0)

您可以从Spring Security Context中获取用户并将其转换为“用户”模型,然后根据需要对其进行处理。在这个例子中,我使用的是@ModelAttribute,你可以在控制器或顾问中添加(@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>

相关问题