Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
962 views
in Technique[技术] by (71.8m points)

jsf 2 - How do a web filter in JSF 2?

I create this filter :

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() {
    }
}

This is my structure:

enter image description here

And then I add the filter in the 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>

The filter works as it should but keeps giving me this error:

"Was not possible find or provider the resource, login"

And after that my richfaces doesn't works anymore.

How can I solve that ? Or create a web filter correctly ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Any path-relative URL (i.e. URLs which do not start with /) which you pass to sendRedirect() will be relative to the current request URI. I understand that the login page is at http://localhost:8080/contextname/login.xhtml. So, if you for example access http://localhost:8080/contextname/pages/user/some.xhtml, then this redirect call will actually point to http://localhost:8080/contextname/pages/user/login.xhtml, which I think don't exist. Look at the URL in your browser address bar once again.

To fix this problem, rather redirect to a domain-relative URL instead, i.e. start the URL with /.

res.sendRedirect(req.getContextPath() + "/login.xhtml");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...