JSF 2中的Web过滤器如何?

Val*_*lva 6 jsf jsf-2 servlet-filters

我创建了这个过滤器:

public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpSession session = req.getSession();

        if (session.getAttribute("authenticated") != null || req.getRequestURI().endsWith("login.xhtml")) {
            chain.doFilter(request, response);
        } else {
            HttpServletResponse res = (HttpServletResponse) response;
            res.sendRedirect("login.xhtml");
            return;
        }

    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的结构:

在此输入图像描述

然后我在web.xml中添加过滤器:

<filter>
    <filter-name>LoginFilter</filter-name>
    <filter-class>filter.LoginFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>LoginFilter</filter-name>
    <servlet-name>Faces Servlet</servlet-name>
</filter-mapping>
Run Code Online (Sandbox Code Playgroud)

过滤器按预期工作,但不断给我这个错误:

"Was not possible find or provider the resource, login"
Run Code Online (Sandbox Code Playgroud)

之后我的富有表面不再适用了.

我怎么解决这个问题?或者正确创建Web过滤器?

Bal*_*usC 9

/您传递给的任何路径相对URL(即不以其开头的URL )sendRedirect()将相对于当前请求URI.我知道登录页面位于http:// localhost:8080/contextname/login.xhtml.因此,如果您例如访问http:// localhost:8080/contextname/pages/user/some.xhtml,则此重定向调用实际上将指向http:// localhost:8080/contextname/pages/user/login.xhtml,我认为不存在.再次查看浏览器地址栏中的URL.

要解决此问题,请改为重定向到域相对URL,即启动URL /.

res.sendRedirect(req.getContextPath() + "/login.xhtml");
Run Code Online (Sandbox Code Playgroud)