前面介绍了资源的概念。资源是保存在实体中的数据,用于定义如何访问它们。例如,default.xml
文件中的配置应用到实体,会在数据库中创建资源。然后将这些资源与Liferay Portal的权限系统一起使用,以确定谁可以对实体执行什么操作。
Liferay Portal提供了完整的API,以管理与Service Builder集成的资源。这个API会自动注入到你的实现类。管理资源,只需在服务的添加和删除方法中调用API。按以下步骤操作:
- In your
guestbook-service
module, openGuestbookLocalServiceImpl.java
from thecom.liferay.docs.guestbook.service.impl
package。 - Just before the
addGuestbook
method’sreturn
statement, add this code:resourceLocalService.addResources(user.getCompanyId(), groupId, userId, Guestbook.class.getName(), guestbookId, false, true, true);
请注意,
resourceLocalService
对象已经存在,可使用。这是由Service Builder自动注入的几个实用程序之一。后面会看到其余的。此代码为Liferay Portal的数据库添加资源以与实体对应(请注意,该资源
guestbookId
已包含在调用中)。最后是三个布尔值。第一个,是否添加Portlet操作权限。如果权限是用于portlet资源的,那么为Ture。由于此权限是针对模型资源(实体)的,因此这里为false
。另外两个是用于添加组和访客权限的设置。如果将这些设置为true,就会在前面的步骤中添加在权限配置文件(default.xml)中定义的默认权限。既然确定这样做,这些布尔值就会被设置为true。 - Next, go to the
updateGuestbook
method. Add a similar bit of code in betweenguestbookPersistence.update(guestbook);
and thereturn
statement:resourceLocalService.updateResources(serviceContext.getCompanyId(), serviceContext.getScopeGroupId(), Guestbook.class.getName(), guestbookId, serviceContext.getGroupPermissions(), serviceContext.getGuestPermissions());
- Now you’ll do the same for
deleteGuestbook
. Add this code in betweenguestbook = deleteGuestbook(guestbook);
and thereturn
statement:resourceLocalService.deleteResource(serviceContext.getCompanyId(), Guestbook.class.getName(), ResourceConstants.SCOPE_INDIVIDUAL, guestbookId);
- Hit [CTRL]+[SHIFT]+O to organize the imports and save the file。
- Now you’ll add resources for the
Entry
entity. OpenEntryLocalServiceImpl.java
from the same package. ForaddEntry
, add a line of code that adds resources for this entity, just before the return statement:resourceLocalService.addResources(user.getCompanyId(), groupId, userId, Entry.class.getName(), entryId, false, true, true);
- For
deleteEntry
, add this code just before thereturn
statement:resourceLocalService.deleteResource( serviceContext.getCompanyId(), Entry.class.getName(), ResourceConstants.SCOPE_INDIVIDUAL, entryId);
- Finally, find
updateEntry
and add its resource action, also just before thereturn
statement:resourceLocalService.updateResources( user.getCompanyId(), serviceContext.getScopeGroupId(), Entry.class.getName(), entryId, serviceContext.getGroupPermissions(), serviceContext.getGuestPermissions());
这就是添加权限资源所需的全部内容。添加到数据库中的未来实体是完全允许的。但是,请注意,已经在门户中添加到Guestbook应用程序中的任何实体都没有资源,因此不能被权限保护。您将在本节的末尾修复这个问题。
接下来,将创建helper类,以便轻松地检查权限。