JSF中的缓存控制

时间:2015-09-01 11:11:44

标签: jsf caching jsf-2 facelets

我有很多使用<ui:composition>的JSF页面。说我有以下页面

  • common.xhtml(此处定义headbody。这是所有网页的父/主/首页。
  • p1.xhtml(包含在common.xhtml中使用<ui:composition>
  • p2.xhtml(包含在common.xhtml中使用<ui:composition>
  • p3.xhtml(使用common.xhtml包含在<ui:composition>中,我希望在此页面点击时重新加载JF和css文件)

我通过this链接,但它不会帮助我,因为我必须将标题放在common.xhtml中(这将停止缓存所有JF和CSS文件,我不想要这个。)

如何在p3.xhtml点击时重新加载js和css文件

修改

我在common.xhtml

中添加了以下内容
<h:head>
   ....
   <ui:insert name="metaTags" />
</h:head>

我在p3.xhtml

中添加了以下内容
<ui:define name="metaTags">
    <meta http-equiv="cache-control" content="max-age=0" />
    <meta http-equiv="cache-control" content="no-cache" />
    <meta http-equiv="expires" content="0" />
    <meta http-equiv="pragma" content="no-cache" />
</ui:define>

但它仍然没有选择我更新的js文件。

1 个答案:

答案 0 :(得分:2)

基于@BalusC评论(感谢评论)我将完全改写我的回答:

您不需要任何Servlet,您可以在实现JSF阶段侦听器的任何JSF生命周期阶段中包含您的逻辑。我已将内容here改编为您的问题。

你只需要在渲染阶段之前实现一个触发器,并在faces-config.xml文件中声明它。

宣言:

<lifecycle>
    <phase-listener id="nocache">com.company.package.CacheControlPhaseListener</phase-listener>
</lifecycle>

阶段监听器代码:

import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpServletResponse;

public class CacheControlPhaseListener implements PhaseListener
{
    private static final long serialVersionUID = 1L;

    @Override
    public PhaseId getPhaseId()
    {
        return PhaseId.RENDER_RESPONSE;
    }

    @Override
    public void afterPhase(PhaseEvent event)
    {
    }

    @Override
    public void beforePhase(PhaseEvent event)
    {
        FacesContext facesContext = event.getFacesContext();
        if("/p3.xhtml".equals(facesContext.getExternalContext().getRequestServletPath())){
            HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
            response.addHeader("Pragma", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
            // Stronger according to blog comment below that references HTTP spec
            response.addHeader("Cache-Control", "no-store");
            response.addHeader("Cache-Control", "must-revalidate");
            // some date in the past
            response.addHeader("Expires", "Mon, 8 Aug 2006 10:00:00 GMT");
        }
    }
}

错误的初始答案:

您可以在define中编写与此类似的p3.xhtml

<ui:define name="nocache">
    <meta http-equiv=... />
    ...
</ui:define>

并在insert

的标题部分写下common.xhtml
<ui:insert name="nocache" />*