Prevent user from seeing previously visited secured page after logout

You can and should not disable the browser back button or history. That’s bad for user experience. There are JavaScript hacks, but they are not reliable and will also not work when the client has JS disabled.

Your concrete problem is that the requested page is been loaded from the browser cache instead of straight from the server. This is essentially harmless, but indeed confusing to the enduser, because s/he incorrectly thinks that it’s really coming from the server.

You just need to instruct the browser to not cache all the restricted JSP pages (and thus not only the logout page/action itself!). This way the browser is forced to request the page from the server instead of from the cache and hence all login checks on the server will be executed. You can do this using a Filter which sets the necessary response headers in the doFilter() method:

public class NoCacheFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;

        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
        response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
        response.setDateHeader("Expires", 0); // Proxies.

        chain.doFilter(req, res);

    // ...

Map this Filter on an url-pattern of interest, for example *.jsp.


Or if you want to put this restriction on secured pages only, then you should specify an URL pattern which covers all those secured pages. For example, when they are all in the folder /app, then you need to specify the URL pattern of /app/*.


Even more, you can do this job in the same Filter as where you’re checking the presence of the logged-in user.

Don’t forget to clear browser cache before testing! 😉

See also:

  • Authentication filter and servlet for login
  • How to control web page caching, across all browsers?

Leave a Comment