【问题标题】:Show user roles in HTML page without bracket在不带括号的 HTML 页面中显示用户角色
【发布时间】:2016-03-24 01:11:44
【问题描述】:

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

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

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

【问题讨论】:

    标签: javascript java html spring-security thymeleaf


    【解决方案1】:

    抱歉,这个帖子迟到了,但这里有一个使用 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>
    

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

    【讨论】:

      【解决方案2】:

      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>
      

      【讨论】:

      • 如果我在数据库中存储没有“ROLE_”的角色,我可能会遇到问题?
      • @luca 我可能弄错了,但我认为 spring-security 会自动添加 ROLE_
      • 此时我使用 ADMIN 和 USER 没有问题。使用以下代码:

        它返回所有角色。唯一的问题是在不同的

        标签中显示元素而不是在同一行

      • @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:block&gt;&lt;/th:block&gt;&lt;/p&gt;
      【解决方案3】:

      我认为您看到了括号,因为“principal.authorities”是一个数组。尝试使用 jstl taglib。

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

      【讨论】:

      • 是的,我看到了括号,因为结果是一个数组。有没有办法避免jstl?我没有在我的项目中使用它
      • 如果你使用 Thymeleaf,你可以使用 th:each 属性。示例:&lt;html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"&gt; ... &lt;p th:each="item : ${principal.authorities}"&gt;&lt;/p&gt;(来自 Thymeleaf 手册)link
      • 变量是通过 sec:authentication='principal.authorities' 返回的,如果我对此进行迭代,我会收到错误
      • 尝试以这种方式声明变量:&lt;sec:authentication property="authorities" var="auth" /&gt;,然后将其与 th:each 一起使用:&lt;div th:each="item : ${auth}"&gt; item.authority &lt;/div&gt;
      • 我答错了,试试把&lt;sec:authentication property="authorities" var="auth" /&gt;换成&lt;sec:authentication property="principal.authorities" var="auth" /&gt;
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-15
      • 1970-01-01
      • 1970-01-01
      • 2019-03-25
      • 1970-01-01
      • 2021-03-16
      • 2016-07-23
      相关资源
      最近更新 更多