Search code examples
resourcesslingjcr

Sling acces to JCR 'var' resource from java code


I am a begginer in Sling and I want find a way to get access and create file in /var resources of JCR.

I tried using ResourceResolver but I can not find the path as example below request.getResourceResolver().getResource("var"); it returns null.

Getting resourceResolver from SlingHttpServletRequest is a good way to get it?


Solution

  • First, JCR paths should always start with a /. So your code was almost correct.

    Change:

    request.getResourceResolver().getResource("var");
    

    To:

    request.getResourceResolver().getResource("/var");
    

    If your ResourceResolver has permissions to read /var, you will get a Resource. Otherwise, you get null. If you get the ResourceResolver from the request, the permissions depend on the permissions of the user doing the request.

    Getting resourceResolver from SlingHttpServletRequest is a good way to get it?

    It depends. There is a lot to say about "where to get your ResourceResolver" from, but to make it simple:

    If you want to limit access to a resource based on a users permissions, you should get the ResourceResolver from a request. In all other situations, get the ResourceResolver from the ResourceResolverFactory.

    The ResourceResolverFactory is its own rabbit hole. So I would point you to the documentation for that:

    https://sling.apache.org/apidocs/sling9/org/apache/sling/api/resource/ResourceResolver.html