2014-10-29 39 views
4

是有辦法的形式春季安全開關的情況下在JSTL標籤

<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> 

的JSP代碼轉換爲另一種形式,類似於以下(不工作)?

<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 taglib功能?

+1

您可以通過創建一個做同樣的事情,Spring標籤自定義標籤做到這一點。但你只會重新發明輪子。 – 2014-10-29 12:27:02

+0

當我記得正確的時候,重新發明車輪,是我一年前爲這個問題找到的唯一解決方案。 – Ralph 2014-10-29 12:43:00

回答

8

您可以使用var屬性<security:authorize/>標籤,這將創造:

一個頁面範圍的變量到其中的標籤 評價的布爾結果將被寫入,允許相同的條件下得到重用 隨後在頁面中沒有重新評估。

<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> 
1

Workarround:當您只有這個簡單的hasRole(XXX)表達式時,則可以有一個包含當前用戶角色的變量。這個變量可以由控制器填充,或者幾乎在所有jsps中都需要它時,Spring彈出HandlerInterceptor或Servlet過濾器(在Spring Security過濾器之後註冊)。