Avoid back button on JSF web application

By default, the browser’s back button does not send a HTTP request to the server at all. Instead, it retrieves the page from the browser cache. This is essentially harmless, but indeed confusing to the enduser, because s/he incorrectly thinks that it’s really coming from the server.

All you need to do is to instruct the browser to not cache the restricted pages. You can do this with a simple servlet filter which sets the appropriate response headers:

public class NoCacheFilter implements Filter {

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

        if (!request.getRequestURI().startsWith(request.getContextPath() + ResourceHandler.RESOURCE_IDENTIFIER)) { // Skip JSF resources (CSS/JS/Images/etc)
            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);

    // ...

(do note that this filter skips JSF resource requests, whose caching actually needs to be configured separately)

To get it to run on every JSF request, set the following annotation on the filter class, assuming that the value of the <servlet-name> of the FacesServlet in your webapp’s web.xml is facesServlet:


Or, to get it to run on a specific URL pattern only, such the one matching the restricted pages, e.g. /app/*, /private/*, /secured/*, or so, set the following annotation on the filter class:


You could even do the very same job in a filter which checks the logged-in user, if you already have one.

If you happen to use JSF utility library OmniFaces, then you could also just grab its CacheControlFilter. This also transparently takes JSF resources into account.

See also:

  • Prevent user from seeing previously visited secured page after logout
  • Authorization redirect on session expiration does not work on submitting a JSF form, page stays the same
  • Is JSF 2.0 View Scope back-button safe?

Leave a Comment