如何在JSF 2中实现网页过滤器?

6
我创建了这个过滤器:
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() {
    }
}

这是我的结构:

enter image description here

然后,在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>

该过滤器的功能正常,但一直出现以下错误:
"Was not possible find or provider the resource, login"

之后我的richfaces就不能正常工作了。

我该怎么解决呢?或者如何正确创建一个web过滤器?


这是一个奇怪的错误信息。你是从其他语言翻译过来的吗?它只是一个HTTP 404错误吗? - BalusC
我是BalusC,来自巴西,因此错误信息显示的是葡萄牙语,你知道如何将Eclipse切换到英语吗?这样我就可以发布原始的错误信息了。 - Valter Silva
2
Eclipse的默认语言取决于平台默认区域设置。因此,如果您的操作系统设置为葡萄牙语,则Eclipse将继承此设置。但是,您可以通过在“eclipse.exe”上指定“-nl [languagecode]”参数来覆盖此设置。例如:eclipse.exe -nl en 将其设置为英语。 - BalusC
1个回答

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。
要解决这个问题,而不是重定向到一个相对于当前请求URI的URL,请重定向到一个基于域名的相对路径的URL,即以/开头。
res.sendRedirect(req.getContextPath() + "/login.xhtml");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接