使用AEM QueryBuilder可以获取引用的内容,以下是一个示例代码:
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolverFactory;
import com.day.cq.search.QueryBuilder;
public class ReferenceContentFetcher {
private ResourceResolverFactory resolverFactory;
private QueryBuilder queryBuilder;
public ReferenceContentFetcher(ResourceResolverFactory resolverFactory, QueryBuilder queryBuilder) {
this.resolverFactory = resolverFactory;
this.queryBuilder = queryBuilder;
}
public void fetchReferencedContent(String referencePath) {
try (ResourceResolver resolver = resolverFactory.getServiceResourceResolver(null)) {
String queryString = "/jcr:root" + referencePath + "//element(*, cq:PageContent)";
Map queryMap = new HashMap<>();
queryMap.put("path", queryString);
queryMap.put("type", "nt:unstructured");
queryMap.put("p.limit", "-1");
Query query = queryBuilder.createQuery(PredicateGroup.create(queryMap), resolver.adaptTo(Session.class));
SearchResult result = query.getResult();
for (Hit hit : result.getHits()) {
Resource resource = hit.getResource();
// 处理引用的内容
// ...
}
} catch (Exception e) {
// 异常处理
}
}
}
上述代码中,referencePath
是引用路径,例如/content/mysite/page1
。首先,我们通过ResourceResolverFactory
和QueryBuilder
获取ResourceResolver
和Query
对象。然后,我们构建查询字符串,将引用路径作为根节点,并限定节点类型为cq:PageContent
。接下来,我们执行查询并处理查询结果中的每个引用内容。你可以根据实际需求进行进一步的处理。请注意,上述代码仅供参考,你可能需要根据自己的需求进行适当的修改。