不在th:each循环中检查用户授权

xnifntxz  于 2021-10-10  发布在  Java
关注(0)|答案(1)|浏览(262)

有几个组织单元,每个单元都有一个自定义角色。在页面上,授权后,您需要显示仅用于此角色(部门)的按钮。此代码适用于:

<div>
  <a th:sec:authorize="hasRole('ROLE_DEP-1')" href="/userPage/department1" type="button">DEP-1</a>
  <a th:sec:authorize="hasRole('ROLE_DEP-2')" href="/userPage/department2" type="button">DEP-2</a>
  <a th:sec:authorize="hasRole('ROLE_DEP-3')" href="/userPage/department3" type="button">DEP-3</a>
  <a th:sec:authorize="hasRole('ROLE_DEP-4')" href="/userPage/department4" type="button">DEP-4</a>
</div>

但我认为手动编写所有细分是不正确的,因为将来可能会添加更多的单元。我决定通过th:each thymeleaf循环来实现:

<div th:each="d : ${departments}">
   <a th:sec:authorize="hasRole('+${d.role.name}+')" href="/userPage/department" type="button" th:text="${d.shortName}"></a>
</div>

但不幸的是,这不起作用,按钮不显示。角色名称显示正确。部门和角色表之间的关系是1:1。我不明白为什么它不起作用。可能需要在该函数中使用特殊语法:
“hasrole('+${d.role.name}+')”

4ngedf3f

4ngedf3f1#

您将需要使用预处理:

<div th:each="d : ${departments}">
   <a sec:authorize="hasRole(' + __${d.role.name}__ +')" href="/userPage/department" type="button" th:text="${d.shortName}"></a>
</div>

相关问题