【问题标题】:CQ5: How to programmatically find out the Resource given a URL?CQ5:如何以编程方式找出给定 URL 的资源?
【发布时间】:2014-02-02 00:37:18
【问题描述】:

根据ResourceResolver接口:

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

有三种方法可以解析资源的路径或请求:

  1. Resource resolve(HttpServletRequest request) 已弃用。从 2.0.4 开始,请改用 resolve(HttpServletRequest, String)。

  2. Resource resolve(HttpServletRequest request, String absPath) 从给定的 absPath 中解析资源,可选地 HttpServletRequest 考虑在内,比如 Host 请求头的值。

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

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

【问题讨论】:

  • 您找到了正确的 API。您的问题是如何在 JSP/Servlet 中使用它?
  • 问题是该API没有接受URL字符串,只有absPath字符串。

标签: aem sling


【解决方案1】:

如果 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 都应该能够被解析。

【讨论】:

  • 我的实验表明 getResource(path) 中的路径根本不接受协议/主机名/端口。所以上面的代码很可能会返回null。
  • 问题是找出给定 URL 字符串的资源。 resolve(String absPath) 中的 absPath 不接受 URL 字符串。使用 resolve() 的例子不是解决方案。
  • 你是对的。资源解析器使用一个获取 URL 的助手,只使用来自 url 的路径并忽略协议/主机/端口。我已更新示例以使用 java.net.URI 在解析之前获取路径。
【解决方案2】:

ResourceResolver 类已实现以返回资源。具体来说,resolve() 函数适用于这种类型的解析。然而,即使有三个重载的 resolve() 函数,它们都不接受 URL 字符串。

鉴于 ResourceResolver 将 HttpServletRequest 作为输入,如果我可以使用 HttpServletRequestWrapper 将给定的 URL 转换(调整)为 HttpServletRequest,那么问题将得到解决。因此,解决方案是实现一个扩展 HttpServletRequestWrapper 的 ResolverRequest 类。

完整的解决方案和代码示例请见“Programmatically find the Sling Resource from a Given a URL

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-31
    • 1970-01-01
    • 1970-01-01
    • 2018-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多