Menu

How to create a node or drop component in AEM using java program?

A simple and easy java code to create/add a node or drop a component in AEM.

In this tutorial, we are dropping an AEM component on AEM page (in a parsys or under a specific node) programmatically. To complete this requirement, we have to write code as follows:

First, we have to create an object of ResourceResolver either using ResourceResolverFactory or using session. In this example, we use ResourceResolverFactory interface service API to create the object of ResourceResolver to get the resource from AEM. (code snippet line # 6)
Now we will get the resource using ResourceResolver and adapt that resource in a JCR Node type, so we can deal with that resource and perform manipulation. ResourceResolver has a method getResource resource which makes AME resource available for manipulation. getResource() method required a relative to as parameter to get that resource. (code snippet line # 7)
Then using JCR API we will add a node under that resource/Node with its name(component name) and type(component type). (code snippet line # 8)
After that, we will set all the required property for that component. (code snippet line # 9-13)

Below is the complete code to drop a component in AEM using java. If you have any doubt please comment your doubt and questions in the comment section.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
@Reference
private ResourceResolverFactory resolverFactory;
ResourceResolver resolver;
private void addNodeOrComponentInAEM() {
 try {
  resolver = resolverFactory.getServiceResourceResolver(null);
  Node jcrContent=resolver.getResource("/content/we-retail/ca/en/men/jcr:content").adaptTo(Node.class);
  Node nextbuttonNode=jcrContent.addNode("nextButton","nt:unstructured");
  nextbuttonNode.setProperty("buttonType", "submit");
  nextbuttonNode.setProperty("componentName", "coralButton");
  nextbuttonNode.setProperty("fieldId", "submit");
  nextbuttonNode.setProperty("fieldLabel", "Next");
  nextbuttonNode.setProperty("sling:resourceType", "granite/ui/components/coral/foundation/button");
  
 } catch (Exception e) {
  
 } 
}

1 comment:

  1. If you want to consult online doctor healwell24 is the best platfrom for online doctor consultation we have best certified doctor to all over india.

    ReplyDelete