JSTL标签中的Spring Security开关案例



有没有办法转换形式的jsp代码

<security:authorize access="hasRole('ROLE_USER')">You're an user</security:authorize>
<security:authorize access="hasRole('ROLE_ADMIN')">You're an admin</security:authorize>
<security:authorize access="hasRole('ROLE_SADMIN')">You're a superadmin</security:authorize>

转换为另一种形式,类似于下面的(不起作用)?

<c:choose>
  <c:when test="hasRole('ROLE_USER')">
    You're an user
  </c:when>
  <c:when test="hasRole('ROLE_ADMIN')">
    You're an admin
  </c:when>
  <c:when test="hasRole('ROLE_SADMIN')">
    You're a superadmin
  </c:when>
  <c:otherwise>
    You have no relevant role
  </c:otherwise>
</c:choose>

更确切地说,有没有一种方法可以用JSTL标签来替代这个Spring Security标签库功能?

您可以使用<security:authorize/>标记的var属性,该属性将创建:

一个页面范围的变量,标记的布尔结果将进入该变量将编写评估,允许重复使用相同的条件随后在页面中,而无需重新评估。

<security:authorize access="hasRole('ROLE_USER')" var="isUser" />
<security:authorize access="hasRole('ROLE_ADMIN')" var="isAdmin" />
<security:authorize access="hasRole('ROLE_SADMIN')" var="isSuperUser" />
<c:choose>
  <c:when test="${isSuperUser}">
    You're a superadmin
  </c:when>
  <c:when test="${isAdmin}">
    You're an admin
  </c:when>
  <c:when test="${isUser}">
    You're an user
  </c:when>
  <c:otherwise>
    You have no relevant role
  </c:otherwise>
</c:choose>

Workarround:当您只有这个简单的hasRole(XXX)表达式时,您就可以有一个包含当前用户角色的变量。这个变量可以由控制器填充,或者当您在几乎所有的jsp中需要它时,可以由Spring HandlerInterceptor或Servlet Filter(在Spring Security Filter之后注册)填充。

最新更新