Search code examples
javajquerysessionstruts2cache-control

Why after logout clicking back button on the page displays previous page content?


I am working on a Struts 2 project. When user clicks a logout button the logout action clears the session using session.clear().

But when user clicks the back button in the browser after logout, it still displays the previous page content.

I want to redirect an user to the login page, if the back button was clicked in the browser after logout.

Is there anything else I should clear in my logout action to solve this problem?


Solution

  • Turns out that your browser is caching pages before you press the back button. The browser caching mechanism is designed so to minimize the server access time by getting the page from the local cache if the page have the same URL. It significantly reduces the server load when browsing the server by thousands of clients and seems to be very helpful. But in some cases, especially in yours the content should be updated. The back button is designed so it caches every page that a user is browsing and retrieve them from the local cache when pressed the back button. So, the solution is to tell the browser to not allow caching when returning a response with a special headers that control the browser caching. In the servlet environment you might use a filter to turn off caching but in Struts2 you could use a custom interceptor. For example

    public class CacheInterceptor implements Interceptor {
    
    private static final long serialVersionUID = 1L;
    
    @Override
    public void destroy() {}
    
    @Override
    public void init() {}
    
    @Override
    public String intercept(ActionInvocation invoication) throws Exception {
        HttpServletRessponse response = ServletActionContext.getResponse();
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "-1");
        return invoication.invoke();
    }
    
    }
    

    Now you could configure this interceptor to use by every action

    <package name="default" extends="struts-default" abstract="true">
    
        <interceptors>
          <interceptor name="cache" class="org.yourcompany.struts.interceptor.CacheInterceptor "/>
          <interceptor-stack name="cacheStack">
            <interceptor-ref name="cache"/>
            <interceptor-ref name="defaultStack"/>
          </interceptor-stack>
        </interceptors>
        <default-interceptor-ref name="cacheStack"/>
    
    </package>
    

    When your packages extend default package they inherit the interceptor and the interceptor stack, you can also override this configuration by the action configuration.