在 HTML 页面中显示用户角色(不带括号)

luc*_*uca 2 html javascript java spring-security thymeleaf

我正在使用 Spring security 对我的网页中的用户进行身份验证。我想向每个用户显示他的角色,不带括号。如果我使用

<p sec:authentication='principal.authorities'></p>
Run Code Online (Sandbox Code Playgroud)

我看到[管理员,用户]。thymeleaf、javascript 或 HTML 有没有办法只显示 ADMIN、USER?我知道在百里香中有弹簧替换,但是我如何传递上面代码的结果?感谢和问候

And*_*rew 5

thymeleaf-extras-springsecurity#authentication提供对可以返回 GrantedAuthorities 列表的对象的访问。分配的每个角色都会有一个 GrantedAuthority(前缀为“ROLE_”)。

您可以使用它来循环并显示每个角色(删除 ROLE_ 前缀):

    <p th:each="authority : ${#authentication.getAuthorities()}"
       th:if="${authority.getAuthority().startsWith('ROLE_')}"
       th:text="${authority.getAuthority().replaceFirst('ROLE_', '')}">
    </p>
Run Code Online (Sandbox Code Playgroud)

  • @luca 嗯,这很容易解决。您可以使用`th:block`,它不会在生成的html中产生任何输出,并使用`iterStat`添加逗号(除了最后一个):`&lt;p&gt;&lt;th:block th:each ="authority, iterStat : ${#authentication.getAuthorities()}"&gt;&lt;th:block th:text="${authority.getAuthority() + (iterStat.last?'':',')}"&gt;&lt; /th:块&gt;&lt;/th:块&gt;&lt;/p&gt;` (2认同)