在JSF中,web.xml配置重定向到登录页面以处理会话超时

4

JSF 中,是否有任何在 web.xml 中的配置可以在会话过期后将应用程序重定向到登录页面。我已经搜索了谷歌,但没有找到好的简单答案。
我找到了这个,但它没有起作用。

 <error-page>
    <exception-type>javax.faces.application.ViewExpiredException</exception-type>
    <location>/faces/index.xhtml</location>
</error-page>

如果没有配置,如何在JSF中实现此操作?谢谢。
3个回答

2

1
另一个可能的答案:如何在jsf应用程序中发生会话超时时重定向到主页 另一个可能的答案:使用JSF PhaseListener
此外,我建议使用一个过滤器来检查您的会话是否已经启动,如果没有,则重定向到您的自定义错误页面(我不记得我是从哪里学到这种方法的,可能是通过BalusC):
public class AuthenticationFilter implements Filter {
    private FilterConfig config;

    public void init(FilterConfig filterConfig) throws ServletException {
        this.config = filterConfig;
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if(((HttpServletRequest) request).getSession().getAttribute("some_attribute_you_store_in_Session") == null){
            ((HttpServletResponse)response).sendRedirect("yourCustomJSF.jsf");
        }else{
            chain.doFilter(request, response);
        }
    }

    public void destroy() {
        this.config = null;
    }

    // You also have to implement init() and destroy() methods.
}

然后,您必须在web.xml中声明此过滤器(以及将触发过滤器的URL模式):

<filter>
    <filter-name>AuthenticationFilter</filter-name>
    <filter-class>yourPackage.AuthenticationFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>AuthenticationFilter</filter-name>
    <url-pattern>private.jsf</url-pattern>
</filter-mapping>

我在我的JSF会话中存储自己的bean,以便保留用户信息。当过滤器在访问类时返回null时,我知道会话已失效(可能是因为它已过期,或者用户已注销),然后将请求重定向到我的错误页面。


如果只是检查 HttpSession,请使用此语法:HttpSession session = request.getSession(false); 如果 (session == null) ...否则它会创建一个新的 session。没有必要使用随机的session变量。 - Darrell Teague

0

我找到了这个,但它没有起作用。

它应该可以工作。很可能你只是使用了ajax请求。这样标准的web.xml错误页面机制就不会被使用。相反,你应该使用JSF的ExceptionHandler工具。

JSF实用库OmniFaces有一个FullAjaxExceptionHandler,专门为此目的设计。它重用标准的web.xml错误页面机制来处理ajax请求期间的异常/错误。你可以在这里找到一个演示案例here。它还处理ViewExpiredException

另请参阅:


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