Как вставить дату последнего изменения в заголовок ответа? - PullRequest
0 голосов
/ 14 декабря 2018

Я пытаюсь добавить дату последнего изменения в исходный код html страниц, обслуживаемых нашей CMS (Jahia), чтобы она отображалась в качестве атрибута в заголовке ответа.

Это необходимо длянаша поисковая система индексации.

Я попытался добавить в тег head следующие синтаксисы, но ни один из них не позволяет изменить дату, указанную в заголовках ответа:

<meta name="dcterms.modified" content="Mon, 09 Apr 2018 11:41:11 GMT">
<meta name="DCTERMS.modified" content="Mon, 09 Apr 2018 11:41:11 GMT">      
<meta http-equiv="last-modified" content="Mon, 09 Apr 2018 11:41:11 GMT">   
<meta http-equiv="Last-Modified" content="Mon, 09 Apr 2018 11:41:11 GMT">   

(эти даты разрешены сthe fmt: formatDate pattern = "EEE, dd MMM гггг чч: мм: сс z").

Неправильно ли я предполагаю, что метатег, добавленный внутри тега заголовка, может быть добавлен в заголовок?Я прочитал на сайте W3Schools, что единственными атрибутами для http-эквивалент являются

<meta http-equiv="content-type|default-style|refresh"> 

, поэтому, вероятно, этот синтаксис не работает (хотя я могу найти ссылки на него в Интернете).

Заранее благодарим за помощь.

Ответы [ 2 ]

0 голосов
/ 15 января 2019

После получения помощи от службы поддержки Jahia я добавил класс фильтра с исходным кодом, чтобы добавить дату последнего изменения в заголовки ответа, и добавил класс в конфигурацию.

  • Сначала вынужно добавить конфигурацию пружины.Вы можете поместить его в XML-файл в \ src \ main \ resources \ META-INF \ spring

    <bean id="ResponseNewestModifFilter"   class="org.jahia.modules.lastmodif.filters.ResponseNewestModifFilter">
    <property name="priority" value="12" />
    <property name="description" value="Set Last Modif date in response header"/>
    <property name="applyOnModes" value="live,preview" />
    <property name="applyOnConfigurations" value="page" />
    </bean>
    
  • , а затем добавить класс фильтра (унаследованный от класса AbstractFilter), который используетМетод addDateHeader,

    package org.jahia.modules.lastmodif.filters;
    import javax.jcr.RepositoryException;
    import org.jahia.modules.lastmodif.taglib.NewestLastModifTag;
    import org.jahia.services.render.RenderContext;
    import org.jahia.services.render.Resource;
    import org.jahia.services.render.filter.AbstractFilter;
    import org.jahia.services.render.filter.RenderChain;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    public class ResponseNewestModifFilter extends AbstractFilter {
    
    private static final Logger logger = LoggerFactory
            .getLogger(ResponseNewestModifFilter.class);
    
    @Override
    public String execute(String previousOut, RenderContext renderContext,
            Resource resource, RenderChain chain) throws Exception {
        try {
            if (renderContext.getResponse().getHeader("Last-Modified") != null) {
                renderContext.getResponse().setDateHeader(
                        "Last-Modified",
                        NewestLastModifTag.getNewestLastModifDateOfPage(
                                resource.getNode()).getTime());
            } else {
                renderContext.getResponse().addDateHeader(
                        "Last-Modified",
                        NewestLastModifTag.getNewestLastModifDateOfPage(
                                resource.getNode()).getTime());
            }
        } catch (RepositoryException ex) {
            logger.error("Error set Last-Modified reponse header", ex);
        }
        return previousOut;
       }
    }
    

Этот класс ссылается на пользовательский taglib (NewestLastModifTag), который обеспечивает запрос всех подузлов для получения даты последнего изменения

package org.jahia.modules.lastmodif.taglib;

import java.util.Calendar;

import javax.jcr.RepositoryException;

import org.jahia.services.content.JCRNodeIteratorWrapper;
import org.jahia.services.content.JCRNodeWrapper;

public class NewestLastModifTag {

    public static java.util.Date getNewestLastModifDateOfPage(org.jahia.services.content.JCRNodeWrapper node) throws RepositoryException {

        if (node.hasNodes()) {
            return getSubnodesWithNewerDate(node, node.getProperty("jcr:lastModified").getDate()).getTime();
        }
        return node.getProperty("jcr:lastModified").getDate().getTime();
    }

    private static Calendar getSubnodesWithNewerDate(JCRNodeWrapper node, Calendar date) throws RepositoryException {

        JCRNodeIteratorWrapper nodes = node.getNodes();
        while (nodes.hasNext()) {
            JCRNodeWrapper snode = (JCRNodeWrapper)nodes.next();
            if (snode.isNodeType("jnt:page")) {
                continue;
            }
            if (snode.hasProperty("jcr:lastModified") && snode.getProperty("jcr:lastModified").getDate().after(date)) {
                date = snode.getProperty("jcr:lastModified").getDate();
            }
            date = getSubnodesWithNewerDate(snode, date);
        }
        return date;
    }

}
0 голосов
/ 14 января 2019

Вы можете включить любые метаданные в заголовочный html, созданный Jahia для ваших страниц.Вот пример вывода html с одной из наших страниц:

<meta name="dcterms.created" content="Mon May 26 08:06:56 CEST 2018" />
<meta name="dcterms.modified" content="Tue Oct 30 10:40:43 CET 2018" />
<meta name="dcterms.issued " content="Wed Oct 31 09:09:53 CET 2018" />

Чтобы получить их, вам нужно использовать текущий узел страницы:

<c:set var="pageNode" value="${jcr:getParentOfType(currentNode, 'jnt:page')}"/>
<c:if test="${empty pageNode}">
    <c:choose>
        <c:when test="${jcr:isNodeType(renderContext.mainResource.node, 'jnt:page')}">
            <c:set var="pageNode" value="${renderContext.mainResource.node}"/>
        </c:when>
        <c:otherwise>
            <c:set var="pageNode" value="${jcr:getParentOfType(renderContext.mainResource.node, 'jnt:page')}"/>
        </c:otherwise>
    </c:choose>
</c:if>

В соответствии сJahia API, вы можете получить следующие свойства страницы:

<c:set var="dateOfCreation" value="${pageNode.creationDateAsDate}" />
<c:set var="dateOfLastModification" value="${pageNode.lastModifiedAsDate}" />
<c:set var="dateOfLastPublication" value="${pageNode.lastPublishedAsDate}" />

и затем вывести их в представление компонента или шаблон:

<c:if test="${!empty dateOfCreation}"><meta name="dcterms.created" content="${fn:escapeXml(dateOfCreation)}" /></c:if>
<c:if test="${!empty dateOfLastModification}"><meta name="dcterms.modified" content="${fn:escapeXml(dateOfLastModification)}" /></c:if>
<c:if test="${!empty dateOfLastPublication}"><meta name="dcterms.issued " content="${fn:escapeXml(dateOfLastPublication)}" /></c:if>
...