Search code examples
jspjsfmyfaces

JSF 2 (MyFaces 2.0.12): Preventing Login page from being Cached issues


To prevent Login screen on my application from being cached by the browser i'm using the following peace of code :

public class SessionHandler implements Filter {


public void init(FilterConfig filterConfig) throws ServletException {
}

public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
    if ((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse)) {
    .
    .
    .
    try {
        HttpServletRequest httpReq = (HttpServletRequest) request;
        HttpServletResponse httpRes = (HttpServletResponse) response;

        //ignore images/css...etc
        if(!httpReq.getRequestURI().startsWith(httpReq.getContextPath() + ResourceHandler.RESOURCE_IDENTIFIER)){
            //if login screen or home - don't cache 
            if(httpReq.getRequestURI().equalsIgnoreCase("/jsp/auth_login.faces")
                    || httpReq.getRequestURI().equalsIgnoreCase("/jsp/def_home.faces") ) {


                System.out.println(httpReq.getRequestURI() + " ----- " + " WON'T BE CACHED");

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

Using code I've found in one of the questions answered here by BalusC to prevent caching. My problem is that it seems the page is still being cached by the browser. Using Chrome Developer Tools to view HTML header of page i see the following on initial page load:

enter image description here

and if go back to login page after successful login i see:

enter image description here

Is anyone able to tell me why the login page is being cached?


Solution

  • Problem was caused due to implicit lookup of request URI where in cases in which the application was not deployed under root path the logic was not being used.

        if(!httpReq.getRequestURI().startsWith(httpReq.getContextPath() + ResourceHandler.RESOURCE_IDENTIFIER)){
            //if login screen or home - don't cache 
            if(httpReq.getRequestURI().equalsIgnoreCase("/jsp/auth_login.faces")
                    || httpReq.getRequestURI().equalsIgnoreCase("/jsp/def_home.faces") ) 
    

    was changed to:

        if(!httpReq.getRequestURI().startsWith(httpReq.getContextPath() + ResourceHandler.RESOURCE_IDENTIFIER)){
            //if login screen or home - don't cache 
            if(httpReq.getRequestURI().endsWith("/jsp/auth_login.faces")
                    || httpReq.getRequestURI().endsWith("/jsp/def_home.faces") ) 
    

    and it's all working as intended.