简体   繁体   中英

Sling resource vs nodes

I'm having trouble understanding why you would use resources instead of nodes in sling. So say I have something simple accessing nodes like below:

NodeIterator headerNode = currentNode.getNodes();
//loop through and do something with the nodes.

How would you work in resources instead of nodes. I've heard you should generally work in resources in sling not nodes. But why? I really don't understand what the benefit to this would be. I think I'm having trouble grasping what resources are as well. I know there's documentation but I can't find any code samples on how to use them.

The main documentation to look at is http://sling.apache.org/documentation/the-sling-engine/resources.html which explains the Resource concept and how you work with them.

The API is somewhat different from the JCR nodes API, but uses similar concepts. The one thing which is definitely simpler with Resources is accessing property values, as you get them in a ValueMap and missing properties don't throw exceptions for example.

The above docs should explain the main patterns, in short those are:

  • You get a Resource from the Sling Request, or using a ResourceResolver service
  • A Resource can be adapted to a ValueMap to access its properties
  • A Resource can be adapted to a Node if you need to switch to the JCR API
  • Resource.listChildren(...) is similar to Node.getNodes()
  • Resource.getResourceResolver() provides a ResourceResolver that gives access to other Resources by searching or by path.

The Resource exists to abstract the content storage, to make it possible to use other backends than JCR in Sling and to unify Sling's view on the data and content that it uses internally.

For application-level programming, in my opinion the JCR API is very nice, I wouldn't use Resource instead just for the sake of it. But there are some cases where the Resource API makes things simpler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM