Question

Suppose I have the following structure

myPage
jcr:content
  ->parContent
      ->myComponent

What is an elegant way to find myComponent if myPage path is known?

I use the following:

private Node myNode(String myPagePath){
    ResourceResolver resourceResolver = request.getResourceResolver();
    Resource resource = resourceResolver.getResource(myPagePath);
    final Node currentNode = resource.adaptTo(Node.class);

    return currentNode.getNode("jcr:content").getNode("parContent").getNode("myComponent");
}

I dont find getNode().getNode().... nice particularry when we have a lot of nodes. Any suggestion?

Was it helpful?

Solution

The getNode(String) method accepts a relative path, so while a child name is is a relative path and frequently how this method is used, you can also construct a relative path:

Node result = currentNode.getNode("jcr:content/parContent/myComponent");

As you can see, it's pretty straightforward. Of course, paths are quite powerful in JCR; see Section 3.4 in the JCR 2.0 specification for a full definition of what's allowed in both absolute and relative paths.

BTW, if you have an absolute path, you must look up the node directly from the Session:

Node result = mySession.getNode("/some/absolute/path/to/a/node");

OTHER TIPS

I discourage the use of the Node API on my development team in JSP's. Instead, the ValueMap interface permits accessing any property, including on paths relative to a page. They don't throw exceptions, and also permit default values if not found.

you can convert Resources to the ValueMap (and you can convert Nodes, Pages to Resource just as easily as to a Node):

ValueMap vm = resource.adaptTo(ValueMap.class);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top