CQ5: How to programmatically find out the Resource given a URL?

15,936

If the hostname/port from the URL is mapped to a content repository location CQ will attempt to resolve the URL supplied.

In a servlet the ResourceResolver can be obtained from the slingRequest:

ResourceResolver resourceResolver = slingRequest.getResourceResolver();
String resourcePath = new URI("http://www.mycompany.com/whatever.html").getPath();
Resource res = resourceResolver.resolve(resourcePath);

Bear in mind that for short urls and domains like the above to work you would need to configure mapping on your instance.

In a JSP, as long as you have called the <sling:defineObjects/> or <cq:defineObjects/> tag you will be able to use:

<sling:defineObjects>
<%
    String resourcePath = new URI("http://www.mycompany.com/whatever.html").getPath();
    Resource res = resourceResolver.resolve(resourcePath);
%>

Some more information is provided in "Getting Resources and Properties in Sling"

Test out on a couple of URLs you know are good. For example:

Resource res = resourceResolver.resolve("http://localhost:4502/content/geometrixx.html");
Resource res = resourceResolver.resolve("/content/geometrixx.html");

Both of the above should resolve to the same resource.

If you want to test whether CQ can resolve the URL you are providing, try the jcr resolver page in the system console http://localhost:4502/system/console/jcrresolver to see if the url is mapped if it does not contain the full /content/.. in the path. Any mapped should be able to be resolved.

Share:
15,936
hko19
Author by

hko19

I'm an entrepreneurial software developer with startup experiences.

Updated on June 14, 2022

Comments

  • hko19
    hko19 about 2 years

    According to ResourceResolver Interface:

    http://dev.day.com/docs/en/cq/current/javadoc/org/apache/sling/api/resource/ResourceResolver.html

    There are three ways to resolve either path or request to a Resource:

    1. Resource resolve(HttpServletRequest request) Deprecated. as of 2.0.4, use resolve(HttpServletRequest, String) instead.

    2. Resource resolve(HttpServletRequest request, String absPath) Resolves the resource from the given absPath optionally taking HttpServletRequest into account, such as the value of the Host request header.

    3. Resource resolve(String absPath) Resolves the resource from the given absolute path.

    But if I have a random given URL string (e.g. http://www.mycompany.com/whatever.html), how do I programmatically find out the corresponding Resource of the given URL?