Resource Sling vs nodes

I am having trouble understanding why you are using resources instead of nodes in sling. So say that I have something with easy access to the nodes, as shown below:

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

How you will work in resources instead of nodes. I heard that you usually have to work in resources in slings, not in nodes. But why? I really don’t understand what is the use of this. I think I have problems understanding what resources are. I know the documentation, but I can not find code samples on how to use them.

+4
source share
1 answer

The main documentation for viewing is http://sling.apache.org/documentation/the-sling-engine/resources.html , which explains the concept of the Resource and how you work with them.

The API is slightly different from the JCR Node APIs, but uses similar concepts. The only thing that is definitely easier in Resources is access to property values, because you get them in ValueMap, and missing properties do not throw exceptions, for example.

In the above documents, the basic patterns should be explained, in short:

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

A resource exists to abstract the content store so that you can use other backends than the JCR in Sling, and unify the Sling view with the data and content that it uses internally.

For programming at the application level, in my opinion, the JCR API is very nice, I would not use Resource instead just for it. But there are some cases where the resource API makes things easier.

+8
source

Source: https://habr.com/ru/post/1481061/


All Articles