需求:

在Liferay中,我们可以用其特有的权限机制来控制视图,比如我们想要页面上某些元素只对某种权限的用户开放。

 

解决:

其实Liferay中有内置的标记和对象可以轻松的达到这些要求,但是我们首先必须在页面上引入正确的标记库:

 
  
  1. <liferay-theme:defineObjects/> 

 

然后我们在页面上,就可以使用user 内置对象来正确的取得其权限了,我们把它封装在一段scriplet中:

 
  
  1. <!-- charles:determine whether the current has the admin privilege --> 
  2.  
  3. <% 
  4.  
  5.                 boolean hasAdminPrivilege= false
  6.  
  7.                 List<Role> userRoles = 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. %> 

比如这段代码我们就是用user内置对象获取它所有的权限,然后判断它是否包含"Administrator"权限,然后吧这个布尔变量保存下来。

 

最后我们就用刚才的boolean变量来正确的进行视图控制,可以配合c标记库一起使用,比如以下代码就实现了只有Admin用户才可以看到"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>