【问题标题】:getRequestDispatcher(" ").forward does not work in JSF 2.0getRequestDispatcher(" ").forward 在 JSF 2.0 中不起作用
【发布时间】:2012-03-19 04:32:55
【问题描述】:

我在使用 JSF 2.0 的应用中有以下代码

    HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
                    .getRequest();
            HttpServletResponse response = (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
......

try {
            request.getRequestDispatcher("SomePage.xhtml").forward(request, response);
        } catch (ServletException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

但是当线..

 request.getRequestDispatcher("SomePage.xhtml").forward(request, response);

执行我得到以下异常...

java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.ArrayList.RangeCheck(ArrayList.java:547)
    at java.util.ArrayList.get(ArrayList.java:322)
    at javax.faces.component.AttachedObjectListHolder.restoreState(AttachedObjectListHolder.java:165)
    at javax.faces.component.UIComponentBase.restoreState(UIComponentBase.java:1432)
    at com.sun.faces.application.view.StateManagementStrategyImpl$1.visit(StateManagementStrategyImpl.java:265)
    at com.sun.faces.component.visit.FullVisitContext.invokeVisitCallback(FullVisitContext.java:151)

由于某些应用程序限制,我无法使用

FacesContext.getCurrentInstance().getExternalContext().redirect();

方法..

这是 JSF 2.0 的错误吗??

【问题讨论】:

  • 好吧,似乎在进行转发之前需要调用一些 JSF 生命周期方法,因为我能够使用正常的 JSF 导航进行转发。知道哪些方法吗??

标签: jsf-2


【解决方案1】:

我从未尝试过以这种方式发送重定向,因为这不是 JSF2 中导航的标准解决方案。

以下是一些可以在 JSF 2.0 环境中正常工作的方法:

1.在导航链接中指定重定向命令

?faces-redirect=true 附加到您的导航中,这应该可以完成工作。

public String someAction(){
    // Logic here
    return "newPage" + "?faces-redirect=true"
}

<h:form id = "form">
    <h:inputText>...</h:inputText>
    <h:commandButton action = "#{controller.someAction}" />
</h:form>

处理someAction 中的登录后,导航流将被重定向到newPage.xhtml。您所要做的就是正确调用 UI 表单中的操作。

2。通过外部上下文指定重定向

这种方法更接近你要找的东西:

public void someAction(){
    // Logic here
    try{
        FacesContext.getCurrentInstance().getExternalContext().redirect("newPage");
    } catch (Exception e){
        e.getMessage();
    }
}

【讨论】:

  • @BalusC 谢谢!我在那里看到了.redirect(),这以某种方式误导了我
【解决方案2】:

首先,当您需要在 JSF 托管 bean 中使用 javax.servlet.* 类时,会发生很大的变化,即您以错误的方式做事或不必要地过于复杂。下次需要添加import javax.servlet...; 行时请记住这一点。

至于您的具体问题,在您的特定情况下,您应该只返回视图 ID 以执行转发。

public String someAction() {
    // ...

    return "SomePage";
}

另一种方法是ExternalContext#dispatch() 方法,但这也不必要地过于复杂。

【讨论】:

    猜你喜欢
    • 2012-09-29
    • 1970-01-01
    • 1970-01-01
    • 2014-08-18
    • 2011-11-26
    • 1970-01-01
    • 2017-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多