需求:
在Liferay中,我們可以用其特有的權限機制來控制視圖,比如我們想要頁面上某些元素隻對某種權限的使用者開放。
解決:
其實Liferay中有内置的标記和對象可以輕松的達到這些要求,但是我們首先必須在頁面上引入正确的标記庫:
<liferay-theme:defineObjects/>
然後我們在頁面上,就可以使用user 内置對象來正确的取得其權限了,我們把它封裝在一段scriplet中:
<!-- charles:determine whether the current has the admin privilege -->
<%
boolean hasAdminPrivilege= false;
List<Role> userRoles = user.getRoles();
for (Role role :userRoles){
if("Administrator".equals( role.getName().trim()) ){
hasAdminPrivilege=true;
break;
}
}
%>
比如這段代碼我們就是用user内置對象擷取它所有的權限,然後判斷它是否包含"Administrator"權限,然後吧這個布爾變量儲存下來。
最後我們就用剛才的boolean變量來正确的進行視圖控制,可以配合c标記庫一起使用,比如以下代碼就實作了隻有Admin使用者才可以看到"delete'按鈕。
<!-- charles:make conclusion that only the Administrator can view the delete button -->
<c:if test="<%=hasAdminPrivilege %>">
<!-- the first time when adminstrator goes to the view mode, he can't see the delete button -->
<!-- because now nothing uploaded ,how it can delete from web server-->
<!-- but after uploaded (heml_url !=null) ,then the delete button is visible to administrator -->
<c:if test="${html_url != null }">
<form action="<portlet:actionURL name="deleteInstance"/>" method="post" name="<portlet:namespace />" class="rs-form">
<input type="submit" value="Delete" class="del"/>
</form>
</c:if>
</c:if>
本文轉自 charles_wang888 51CTO部落格,原文連結:http://blog.51cto.com/supercharles888/1004274,如需轉載請自行聯系原作者