Search code examples
javaaem

How to check if the page has content?


I would like to avoid activating some page if its content is empty. I do this with some servlet as follow:

@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);
    }

Now how to check, if currentPage has content?


Solution

  • Please note that the following answer was posted in 2013 when CQ/AEM was a lot different to the current version. The following may not work consistently if used. Refer to Tadija Malic's answer below for more on this.

    The hasContent() method of the Page class can be used to check whether the page has content or not. It returns true if the page has jcr:content node, else returns false.

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

    In case you would like to check for pages that have not been authored, one possible way is to check if there are any additional nodes that are present under jcr:content.

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