如何检查页面是否有内容?

时间:2013-11-11 11:44:15

标签: java cq5

如果内容为空,我想避免激活某个页面。我用一些servlet执行此操作,如下所示:

@SlingServlet(paths = "/bin/servlet", methods = "GET", resourceTypes = "sling/servlet/default")
public class ValidatorServlet extends SlingAllMethodsServlet {

    @Override
    protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) {
        String page = "pathToPage";
        PageManager pageManager = request.adaptTo(PageManager.class);
        Page currentPage = pageManager.getPage(page);
        boolean result = pageHasContent(currentPage);
    }

现在如何查看currentPage是否有内容?

3 个答案:

答案 0 :(得分:2)

Page类的hasContent()方法可用于检查页面是否包含内容。如果页面具有 jcr:content 节点,则返回true,否则返回false。

boolean result = currentPage != null ? currentPage.hasContent() : false;

如果您想检查尚未创作的页面,可能的一种方法是检查jcr:content下是否存在任何其他节点。

Node contentNode = currentPage.getContentResource().adaptTo(Node.class);
boolean result = contentNode.hasNodes();

答案 1 :(得分:2)

我将创建一个OSGi服务,该服务根据您设置的规则获取页面并遍历其内容树,以确定该页面是否具有有意义的内容。

页面是否具有实际内容是特定于应用程序的,因此创建自己的服务将使您完全控制该决定。

答案 2 :(得分:0)

一种方法是 create a new page using the same template 然后遍历节点列表并计算组件的散列(或它们的内容,具体取决于您要比较的内容)。 获得空页面模板的哈希值后,您就可以将任何其他页面的哈希值与它进行比较。

注意:此解决方案需要适应您自己的用例。也许你检查一下页面上有哪些组件和它们的顺序就足够了,也许你还想比较它们的配置。

private boolean areHashesEqual(final Resource copiedPageRes, final Resource currentPageRes) {
    final Resource currentRes = currentPageRes.getChild(com.day.cq.commons.jcr.JcrConstants.JCR_CONTENT);
    return currentRes != null && ModelUtils.getPageHash(copiedPageRes).equals(ModelUtils.getPageHash(currentRes));
}

模型实用程序:

public static String getPageHash(final Resource res) {
    long pageHash = 0;

    final Queue<Resource> components = new ArrayDeque<>();
    components.add(res);

    while (!components.isEmpty()) {
        final Resource currentRes = components.poll();

        final Iterable<Resource> children = currentRes.getChildren();
        for (final Resource child : children) {
            components.add(child);
        }
        pageHash = ModelUtils.getHash(pageHash, currentRes.getResourceType());
    }

    return String.valueOf(pageHash);
}

/**
 * This method returns product of hashes of all parameters
 * @param args
 * @return int hash
 */
public static long getHash(final Object... args) {
    int result = 0;
    for (final Object arg : args) {
        if (arg != null) {
            result += arg.hashCode();
        }
    }
    return result;
}

注意:使用 Queue 也会考虑组件的顺序。

这是我的方法,但我有一个非常具体的用例。通常,您需要考虑是否真的要计算要发布的每个页面上每个组件的哈希值,因为这会减慢发布过程。 您还可以在每次迭代中比较哈希值,并在第一个差异处中断计算。

相关问题