java - 需要更改使用的名称 sec :authentication in thymeleaf

标签 java spring-security thymeleaf

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

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

相关文章:

jsp - 如何为 Spring Security hasRole 使用常量

java - Thymeleaf - 加载一次元数据并在所有页面上使用

java - 如何计算Java中两个日期之间的年月年龄

java - 如何在授权 Java 程序写入 Web 服务器文件夹时保护它

java - 如何在 Struts 2 上使用 Spring Security 3?

java - Ajax 调用的 Spring security session 超时处理

java - 当字符串的长度发生变化时,如何从字符串中获取数字?

java - 包含整数和字符串的数组列表

java - 为 POST 请求绑定(bind) Thymeleaf 模板上嵌入的对象列表

java - 在 thymeleaf 中使用迭代变量