2012-08-17 75 views
1

我寫了一個攔截器來防止緩存但頁面仍然緩存。清除緩存攔截器struts2不工作

攔截:

public class ClearCacheInterceptor implements Interceptor { 
    public String intercept(ActionInvocation invocation)throws Exception{ 
     String result = invocation.invoke(); 

     ActionContext context = (ActionContext) invocation.getInvocationContext(); 
     HttpServletRequest request = (HttpServletRequest) context.get(StrutsStatics.HTTP_REQUEST); 
     HttpServletResponse response=(HttpServletResponse) context.get(StrutsStatics.HTTP_RESPONSE); 

     response.setHeader("Cache-Control", "no-store"); 
     response.setHeader("Pragma", "no-cache"); 
     response.setDateHeader("Expires", 0); 

     return result; 
    } 

    public void destroy() {} 
    public void init() {} 
} 

struts.xml的

<struts> 
    <constant name="struts.devMode" value="true"/> 
    <constant name="struts.enable.DynamicMethodInvocation" value="false" /> 

    <package name="default" extends="struts-default"> 
    <interceptors> 
     <interceptor name="caching" class="com.struts.device.interceptor.ClearCacheInterceptor"/> 
     <interceptor-stack name="cachingStack">  
     <interceptor-ref name="caching" />  
     <interceptor-ref name="defaultStack" />  
     </interceptor-stack> 
    </interceptors> 

    <action name="Login" class="struts.device.example.LogIn"> 
     <interceptor-ref name="cachingStack"/> 
     <result>example/Add.jsp</result> 
     <result name="error">example/Login.jsp</result> 
    </action> 
    </package> 
</struts> 

應用正常工作;它執行攔截器,但不防止緩存。

+0

通過「它不清除緩存」你的意思是「它仍然緩存」? – 2012-08-17 15:57:00

+0

yes ..... @ DaveNewton – Srishti123 2012-08-17 16:40:52

+0

使用Firebug或Chrome的開發人員工具查看響應,看看是否正在設置HTTP標頭(Cache-Control,Pragma和Expires)。 – 2012-08-17 18:03:47

回答

1

我已經解決了我的問題。感謝幫助我追蹤的開發人員工具。

在我的代碼略有序列改變幫了我:按the Struts 2 interceptor docs結果之前invocation.invoke()回報呈現。在結果返回給客戶端之前設置標題會在返回的結果中設置標題。

public String intercept(ActionInvocation invocation)throws Exception{ 
    HttpServletResponse response = ServletActionContext.getResponse(); 

    response.setHeader("Cache-Control", "no-store"); 
    response.setHeader("Pragma", "no-cache"); 
    response.setDateHeader("Expires", 0); 

    return invocation.invoke(); 
}