Spring Thymeleaf#lists.contains无法正常工作

时间:2017-03-21 22:06:00

标签: spring spring-security thymeleaf

我的最终目标是使用当前用户没有的角色填充下拉列表。

<p th:text="${Item.granted_authorities}"></p>

打印出 [true,true,true]

<p th:text="${#lists.toList(Item.granted_authorities)}"></p>

打印出 [Ljava.lang.Object; @ 63a6ff07

<div th:with="RoleList=${#lists.toList(activeSessionsItem.granted_authorities)}">
<p th:text="${#lists.contains(RoleList, RoleList[0])}"></p>
</div>

打印出 [ROLE_ADMIN,ROLE_SUPERADMIN,ROLE_USER]

<div th:with="RoleList=${#lists.toList(activeSessionsItem.granted_authorities)}">
<p th:text="${#lists.contains(RoleList, 'ROLE_USER')}"></p>
</div>

打印出 true

{{1}}

打印出 false

3 个答案:

答案 0 :(得分:0)

<select th:with="myAuthoritiesList=${myAuthorities}" >
    <option 
        th:each="r : ${allAuthorities}" 
        th:if="${not #lists.contains(myAuthoritiesList, r)}"
        th:value="${r.authority}" 
        th:text="${r.authority}">
    </option>
</select>




@RequestMapping("/home")
public String home(Model m) {
    GrantedAuthority authAdmin = new SimpleGrantedAuthority("ROLE_ADM");
    GrantedAuthority authUser = new SimpleGrantedAuthority("ROLE_USR");

    List<GrantedAuthority> allAuths = new ArrayList<>() ;
    allAuths.add(authAdmin);
    allAuths.add(authUser);
    m.addAttribute("allAuthorities", allAuths);

    List<GrantedAuthority> myAuths = new ArrayList<>() ;
    myAuths.add(authUser);
    m.addAttribute("myAuthorities", myAuths);

    return "home";
}

结果:只选择ROLE_ADM

的选择

答案 1 :(得分:0)

我必须将user_roles转换为字符串。

comments

答案 2 :(得分:-1)

RoleList是GrantedAuthority的列表。

contains()始终返回false,因为GrantedAuthority对象永远不会等于String。

要填充下拉列表,您可以使用此代码,但需要在模型中添加availableAuthorities

<select>
    <option 
       th:each="r : ${availableAuthorities}"
       th:value="${r.authority}" 
       th:text="${r.authority}">
    </option>
</select>