In the previous session, we have seen how to obtain a Resource. We later, translated the Resource into a Page object, and then programmatically obtained its title. We will see one more example. Here, using an AEM bundle, we will write a property to the Page we created. In this case too, we need to use a Resource object to obtain a Session object using which we can save what we write.
Let us start:
- Create a new interface: SearchService.java.
(There is a reason for using this name. In the next session, we are going to discuss about searching.)
- Add the following method.
public void addProperty();.
- Create the implementation class: SearchServiceImpl.java
- Implement the addProperty() method.
- Get the ResourceResolver.
(Visit the previous post to see what the code accomplishes.)
Map<String, Object> param = new HashMap<String, Object>(); param.put(ResourceResolverFactory.SUBSERVICE, "readService"); ResourceResolver resourceResolver=null; resourceResolver = resolverFactory.getServiceResourceResolver(param);
- Obtain the resource.
Resource pageResource = resourceResolver.getResource("/content/aem-company/jcr:content");
Note that we need to add the property to the jcr:content node of the page we created.
- Translate the resource into a node using the adaptTo() class.
Node myNode = pageResource.adaptTo(Node.class);
- Set a property to the node.
- Obtain the session from resourceResolver.
Session session = resourceResolver.adaptTo(Session.class);
- Save the session:
- Deploy the bundle.
- Add a method in the bundleservice component.
<% com.aemcompany.myproject.SearchService searchService=sling.getService(com.aemcompany.myproject.SearchService.class); searchService.addProperty(); %>
- Access the page so that the method is called.
- Log into CRXDELite.
- See the page properties and ensure that the new property is added.
That’s it. See you soon.