0

一旦用户在 cq 对话框中提供文件路径,我需要获取父文件夹名称(字符串类型)。这是我的方法:

import lombok.Getter;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.models.annotations.DefaultInjectionStrategy;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.injectorspecific.*;

import javax.annotation.PostConstruct;
import javax.inject.Inject;
@Getter
@Model(adaptables = {
    Resource.class,
    SlingHttpServletRequest.class
  },
  defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)

public class Test {
  @SlingObject
  private Resource resource;
  @OSGiService
  private ResourceResolver resourceResolver;

  @ValueMapValue
  private String fileUrl;

  @PostConstruct
  public String getData() {
    Resource resource = resourceResolver.getResource(fileUrl);
    Resource parentProps = resource.getParent();
    System.out.println("parent node is =>" + parentProps);
  }
}

有问题吗?我的代码正确构建但不返回任何内容

4

2 回答 2

0

我建议您熟悉调试代码,这样您就可以准确了解幕后发生的事情,而不仅仅是添加日志语句。此外,不完全确定 System.out.println 调用的记录位置,但您可以使用 slf4j 记录器在 /crx-quickstar/logs/error.log 中找到记录信息。我所做的是在我的本地实例上将日志级别配置为 ERROR,以便更容易找到我的日志记录语句

正如Ameesh所说,您需要使用@SlingObject注入ResourceResolver,尽管您可以只使用@ResourcePath为您完成所有资源解析的注释:

@Getter
@Model(adaptables = Resource.class,
  defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)

public class Test {

  private static final Logger LOG = LoggerFactory.getLogger(Test.class);
  
  @Self
  private Resource resource;

  @ResourcePath(name = "fileUrl")
  private Resource file;

  @PostConstruct
  public String getData() {
    final String path = Optional.ofNullable(file)
                          .map(file -> file.getParent())
                          .map(parent -> parent.getPath())
                          .orElse("resource not found!");
    LOG.error("parent node is: {}", path);
  }
}
于 2020-12-03T17:38:42.727 回答
0

ResourceResolver 不是 OSGI 服务,它的 SlingObject

您还需要确保发出请求的登录用户对文件路径具有正确的访问设置

于 2020-10-19T00:31:57.247 回答