在Liferay中,如果我们想要在页面上进行权限控制,比如只有指定权限的用户能看到一些内容,那么我们可以用Liferay预定义的user对象来获取这个对象所拥有的权限,然后再控制页面的显示.

 

为了在liferay页面上使用user对象,我们必须加入标记库:

 
  
  1. <liferay-theme:defineObjects/> 

 

然后我们可以在页面上,直接使用user对象,来控制权限,比如我们可以将当前用户是否为管理员用户的存入到一个布尔变量中,如下:

 
  
  1. <!-- charles:determine whether the current has the admin privilege --> 
  2.  
  3. <
  4.  
  5.                 boolean hasAdminPrivilegefalse
  6.  
  7.                 List<Role> useruserRoles = user.getRoles(); 
  8.  
  9.                 for (Role role :userRoles){ 
  10.  
  11.                                 if("Administrator".equals( role.getName().trim()) ){ 
  12.  
  13.                                                 hasAdminPrivilege=true
  14.  
  15.                                                 break; 
  16.  
  17.                                 } 
  18.  
  19.                 } 
  20.  
  21.                 
  22.  
  23. %> 
  24.  
  25.   

 

然后我们在页面中使用这个布尔变量值来控制显示和不显示某些元素,比如我们的例子中,只有管理员用户才可以看到和操作有"Delete"按钮的表单:

 
  
  1. <!-- charles:make conclusion that only the Administrator can view the delete button  --> 
  2.  
  3.   
  4.  
  5. <c:if test="<%=hasAdminPrivilege %>"> 
  6.  
  7.   
  8.  
  9.                 <!--  the first time when adminstrator goes to the view mode, he can't see the delete button --> 
  10.  
  11.                 <!--  because now nothing uploaded ,how it can delete from web server--> 
  12.  
  13.                 <!--  but after uploaded (heml_url !=null) ,then the delete button is visible to administrator --> 
  14.  
  15.                 <c:if test="${html_url != null }"> 
  16.  
  17.                 
  18.  
  19.                 <form action="<portlet:actionURL name="deleteInstance"/>" method="post" name="<portlet:namespace />" class="rs-form">               
  20.  
  21.                                       <input type="submit" value="Delete" class="del"/> 
  22.  
  23.                 </form> 
  24.  
  25.                 
  26.  
  27.                 </c:if> 
  28.  
  29.                 
  30.  
  31. </c:if> 
  32.  
  33.