【问题标题】:Redirect when a ViewExpiredException is thrown within ajax request在 ajax 请求中抛出 ViewExpiredException 时重定向
【发布时间】:2014-09-24 18:29:48
【问题描述】:

我在 ajax 请求中处理 ViewExpiredExceptions 时遇到问题。 在我的特殊情况下,它是一个rich:datascroller,它会产生问题。我使用omnifaces 1.8.1 的FullAjaxExceptionHandler 来处理Ajax 组件抛出的VEE。

web.xml:

<error-page>
        <exception-type>javax.faces.application.ViewExpiredException</exception-type>
        <location>/my/pages/error/viewExpired.xhtml</location>
</error-page>

viewExpired.xhtml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml"
        xmlns:f="http://java.sun.com/jsf/core"
        xmlns:h="http://java.sun.com/jsf/html">
    <f:event type="preRenderView" listener="#{viewExpiredHandler.handle}" />
</html>

还有 Java 类:

@Named
@RequestScoped
public class ViewExpiredHandler {

    public void handle() {
                String outcome = "/path/to/home.xhtml";
                //Version 1 *************
             try {
                ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
                String redir = ec.getRequestContextPath() + outcome;
                ec.redirect(redir);
            } catch (IOException e) {
                ...
            }
                //Version 2 ************
        FacesContext fc = FacesContext.getCurrentInstance();
        ExternalContext ec = fc.getExternalContext();
        fc.setViewRoot(fc.getApplication().getViewHandler().createView(fc, outcome));
        fc.getPartialViewContext().setRenderAll(true);
        fc.renderResponse();
        }
}

如果会话到期并且我单击数据滚动按钮,我会看到我的 handle() 方法被调用,但转发到主页不起作用。

版本 1 什么都没有发生,版本 2 我首先得到一个空白屏幕,如果我用浏览器按钮刷新页面,handle() 方法会再次被调用并成功重定向到主页

你能看到我的代码中有什么错误吗?

【问题讨论】:

    标签: jsf-2 richfaces omnifaces


    【解决方案1】:

    重定向无效,因为FullAjaxExceptionHandler 完全接管了渲染,因此JSF 无法将ajax 重定向写入响应。更改视图没有效果,因为此时FullAjaxExceptionHandler 已经掌握了错误页面视图,并且不会咨询FacesContext 更改视图。你得到一个空白屏幕,因为你的错误页面本身是空白的。

    让浏览器自行重定向。使用 JS window.location。将您的整个 viewExpired.xhtml 页面替换为以下内容:

    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
        <body>
            <script>window.location="#{request.contextPath}/path/to/home.xhtml";</script>
        </body>
    </html>
    

    【讨论】:

    • 嗨,BalusC!感谢您的回答。不幸的是,此解决方案仅适用于 Chrome。 Firefox 和 IE 8(实际上是我必须支持的唯一浏览器)继续显示空白页面。我注意到,空白页面的 html“头”与 VEE 发生的地方相同。该应用程序使用 servlet 过滤器,它既不改变响应也不产生 sendRedirect():我是否必须特别检查其他东西?谢谢!
    • 您的 ajax 是否由 RichFaces 处理?我用替代方法更新了答案。
    • 是的。并使用 Javascript 重定向工作! :) 再次感谢您!
    猜你喜欢
    • 2016-01-13
    • 2014-05-19
    • 1970-01-01
    • 2016-02-20
    • 2012-02-28
    • 2020-10-19
    • 2018-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多