使用Spring在标题中显示用户信息

问题描述 投票:0回答:2

我正在使用Spring和Thymeleaf,我试图在标题中显示所有页面中的用户信息(用户名)。

了header.html

<div th:fragment="logout" class="logout" sec:authorize="isAuthenticated()">     
        Logged in user: <span sec:authentication="name"></span> |                   
        Roles: <span sec:authentication="principal.authorities"></span>             
        <div>
            <form action="#" th:action="@{/logout}" method="post">                  
                <input type="submit" value="Logout" />
            </form>
        </div>
    </div>

但它没有显示任何东西

spring spring-boot spring-security thymeleaf
2个回答
0
投票

将依赖项添加到适当版本的org.thymeleaf.extras:thymeleaf-extras-springsecurity4

然后将xmlns添加到html中

<html xmlns:th="http://www.thymeleaf.org"
            xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">

你可以做到

<div th:text="${#authentication.name}">
    The value of the "name" property of the authentication object should appear here.
</div>

有关更多信息Spring Security Integration module


0
投票

这个问题的解决方案:

第1步:创建一个CommunAdviceController

public class CommunAdviceController {

@Autowired
UtilisateurRepository utilisateurRepository;

@ModelAttribute("nomEtPrenom")
public String nomEtPrenomUtilisateur() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    Utilisateur util = utilisateurRepository.findByEmail(authentication.getName()) ;    
    if( util != null) {         
        return util.getUsername();
    }else {
    return "Anonyme";
    }
}

}

请注意,在我的情况下,我得到用户的邮件地址为getUsername

第2步:在HTML中调用方法

<a href ="#" th:text="${nomEtPrenom}" class="nav-link dropdown-toggle"  id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">      

工作完成了。

希望它会帮助某人。

© www.soinside.com 2019 - 2024. All rights reserved.