最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Show user roles in HTML page without bracket - Stack Overflow

programmeradmin3浏览0评论

I'm using Spring security to authenticate user in my web page. I would like to show for each user his roles without bracket. If I use

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

I see [ADMIN, USER]. Is there a way in thymeleaf, javascript or HTML to show only ADMIN,USER? I know that in thymeleaf there is spring replace but how can I pass the result of above code? Thanks, regards

I'm using Spring security to authenticate user in my web page. I would like to show for each user his roles without bracket. If I use

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

I see [ADMIN, USER]. Is there a way in thymeleaf, javascript or HTML to show only ADMIN,USER? I know that in thymeleaf there is spring replace but how can I pass the result of above code? Thanks, regards

Share Improve this question asked Dec 17, 2015 at 14:16 lucaluca 3,32811 gold badges69 silver badges149 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

thymeleaf-extras-springsecurity provides access to an #authentication object which can return the list of GrantedAuthorities. There will be a GrantedAuthority for each role assigned (prefixed by 'ROLE_').

You can use this to loop through and display each role (removing the ROLE_ prefix):

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

Sorry, late to this thread, but here is a working solution using Thymeleaf and 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>

The code above will add a ma except after the last role.

I think you see the brackets because 'principal.authorities' is an array. Try with the jstl taglib.

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

评论列表(0)

  1. 暂无评论