In CQ5 everything stores in the form of content ( Nodes and Properties ), but while reading content from repository the apache sling framework assumes this is a Resource.Because the sling follows REST based architecture
In this article I am going to explore how to read properties of a Node
<%@page import="org.apache.sling.api.SlingHttpServletRequest"%>
<%@include file="/libs/foundation/global.jsp"%>
<%@page import="org.apache.sling.api.resource.ResourceResolver"%>
<%
By using CRXDE I am going to create component called "PropertyReader" and going to read properties of this component
In CQ5 everything stores in the form of content that means "PropertyReader" component also exists in content repository
the below code will send a request to server and tries to return Resource object if it does not find any resource then it returns Null
We need to use SlingHttpServletRequest object to communicate with CQ5 CRX, here the slingRequest is avariable which is already defined in global.jsp file
ResourceResolver resolver = slingRequest.getResourceResolver();
Resource res = resolver.getResource("/apps/mspbox/components/PropertyReader");
If needed you can adapt a Sling Resource to a JCR Node like below code Node.class, if you are going to read DAM Assets then you need to use Asset.class
Code :
<%@page import="org.apache.sling.api.SlingHttpServletRequest"%>
<%@include file="/libs/foundation/global.jsp"%>
<%@page import="org.apache.sling.api.resource.ResourceResolver"%>
<%
ResourceResolver resolver = slingRequest.getResourceResolver();
Resource res = resolver.getResource("/apps/mspbox/components/PropertyReader");
Accessing a Property :
Node rootNode = res.adaptTo(Node.class);
ValueMap prop = res.adaptTo(ValueMap.class);
String group = prop.get("componentGroup", (String) null);
out.print(group);
Reading all properties :
if(rootNode!=null) {
NodeIterator children = rootNode.getNodes();
while (children.hasNext()) {
Node node = children.nextNode();
if(node != null) {
PropertyIterator pi= node.getProperties();
out.print("<table>");
while (pi.hasNext()) {
Property p = pi.nextProperty();
out.print("<tr><td>");
out.print(p.getName());
out.print(p.getPath());
out.print("</td></tr>");
}
out.print("</table>");
}
}
};
%>
OUTPUT :
General
cq:layout
jcr:createdBy
jcr:created
cq:dialogMode
jcr:primaryType
Monday, June 11, 2012
CQ5 Reading Node Properties
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment