且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用登录过滤器时缺少JSF页面样式

更新时间:2023-12-03 20:52:52

此过滤器还将CSS/JS/图像文件上的所有请求重定向到登录页面.浏览器最终得到的响应包含一些表示登录页面的HTML代码,而不是其请求的具体CSS/JS/图像内容,因此浏览器无法应用必要的外观.

This filter also redirects all requests on CSS/JS/image files to the login page. The browser end up getting a response containing some HTML code representing the login page instead of the concrete CSS/JS/image content it requested for and hence the browser fails applying the necessary look'n'feel.

假设您100%使用JSF资源管理(<h:outputStylesheet>等),因此它们都被/javax.faces.resource/* URI覆盖,请按如下所示重写过滤器:

Provided that you're 100% utilizing JSF resource management (<h:outputStylesheet>, etc) and thus they are all covered by /javax.faces.resource/* URIs, rewrite your filter as follows:

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {    
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    HttpSession session = request.getSession(false);

    LoginBean auth = (session != null) ? session.getAttribute("loginBean") : null;
    String loginURL = request.getContextPath() + "/faces/login.xhtml";

    boolean loggedIn = auth != null && auth.isLoggedIn();
    boolean loginRequest = request.getRequestURI().equals(loginURL);
    boolean resourceRequest = request.getRequestURI().startsWith(request.getContextPath() + "/faces" + ResourceHandler.RESOURCE_IDENTIFIER);

    if (loggedIn || loginRequest || resourceRequest)) {
        if (!resourceRequest) {
            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(request, response);
    } else {
        response.sendRedirect(loginURL);
    }
}

请注意,不应在资源请求上设置无缓存标头,否则您将失去CSS/JS/图像文件的浏览器缓存优势.

Note that no-cache headers should not be set on resource requests, otherwise you defeat the benefit of the browser cache on CSS/JS/image files.