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

标签 aem sling

根据ResourceResolver接口(interface):

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

可以通过三种方式解析资源的路径或请求:

  1. 资源解析(HttpServletRequest 请求) 已弃用。从 2.0.4 开始,请改用resolve(HttpServletRequest, String)。

  2. 资源解析(HttpServletRequest request, String absPath) 从给定的absPath解析资源(可选) 考虑到HttpServletRequest,例如Host请求头的值。

  3. 资源解析(String absPath) 从给定的绝对路径解析资源。

但是,如果我有一个随机给定的 URL 字符串(例如 http://www.mycompany.com/whatever.html),我如何以编程方式查找给定 URL 的相应资源?

最佳答案

如果 URL 中的主机名/端口是 mapped to a content repository location CQ 将尝试解析提供的 URL。

在 servlet 中,可以从 slingRequest 获取 ResourceResolver:

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

请记住,要使上述短网址和域正常工作,您需要配置 mapping在您的实例上。

在JSP中,只要调用了<sling:defineObjects/><cq:defineObjects/>您将能够使用的标签:

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

"Getting Resources and Properties in Sling" 中提供了更多信息。

测试几个您认为不错的网址。例如:

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

以上两者都应解析为相同的资源。

如果您想测试 CQ 是否可以解析您提供的 URL,请尝试系统控制台中的 jcr 解析器页面 http://localhost:4502/system/console/jcrresolver查看 url 是否已映射(如果路径中不包含完整的/content/..)。任何mapped应该可以解决。

关于aem - CQ5 : How to programmatically find out the Resource given a URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21105300/

相关文章:

javascript - 禁用 Touch UI cq 对话框上的文本字段

java - Adobe CQ5 - 从外部数据库填充下拉列表

aem - 如何在 sling 中复制节点树?

apache - tomcat上部署sling+jackrabbit的优点?

osgi - 如何添加cq :listener to a component

adobe - 如何为 Adob​​e CQ5 创建一个 ajax 搜索组件

maven - Sling 部署内容并使用 Maven 进行捆绑

java - ReplaceSelector 和包含文件之间的区别

java - Sling调度器方法重构

aem - 将 CQ5 表单重用到 mywebsite 组件中不会显示“表单结尾”部分