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

Show user roles in HTML page without bracket

我正在使用 Spring 安全性来验证我网页中的用户。我想为每个用户展示他的角色而不带括号。 如果我使用

<p sec:authentication='principal.authorities'></p>

我看到 [管理员,用户]。 thymeleaf、javascript 或 HTML 中有没有办法只显示 ADMIN、USER? 我知道在 thymeleaf 中有 spring replace 但是我怎样才能传递上面代码的结果呢? 谢谢,问候

我想你看到括号是因为 'principal.authorities' 是一个数组。尝试使用 jstl 标签库。

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<c:forEach var="item" items="principal.authorities">
   <c:out value="${item}"/>
</c:forEach>
...

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

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

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

抱歉,这个帖子来晚了,但这里有一个使用 Thymeleaf 和 Thymeleaf Extras

的有效解决方案
Role(s):
<th:block th:each="r, iter:${#authentication.getAuthorities()}">
    <span th:text="${r}"></span>
    <th:block th:if="${!iter.last}">, </th:block>
</th:block>

上面的代码会在最后一个角色之后添加一个逗号。