0

为了防止我的应用程序上的登录屏幕被浏览器缓存,我使用了以下代码和平:

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);
    ...

使用我在此处回答的问题之一中找到的代码BalusC来防止缓存。我的问题是该页面似乎仍在被浏览器缓存。使用 Chrome 开发人员工具查看页面的 HTML 标题,我在初始页面加载时看到以下内容:

在此处输入图像描述

如果成功登录后返回登录页面,我会看到:

在此处输入图像描述

有谁能告诉我为什么登录页面被缓存?

4

1 回答 1

0

问题是由于请求 URI 的隐式查找引起的,在这种情况下,如果应用程序未部署在根路径下,则未使用逻辑。

    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") ) 

改为:

    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") ) 

这一切都按预期工作。

于 2012-05-01T02:20:54.770 回答