天天看点

Liferay 用权限控制视图

需求:

在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,如需转载请自行联系原作者

继续阅读