jsf中的异常处理 - 在新页面中打印错误消息

Kar*_*yan 5 jsf jsf-2

我只想在发生异常时在错误页面上打印自定义消息.

我试过这个

    if(erroroccured){
        FacesMessage message=new FacesMessage("You must login to continue");
        context.addMessage(null, message);
        FacesContext.getCurrentInstance().getExternalContext().redirect("error.xhtml");

    }
Run Code Online (Sandbox Code Playgroud)

在error.xhtml我给了

    <h:messages></h:messages>
Run Code Online (Sandbox Code Playgroud)

标签也..每当发生异常时我的页面都被完美地重定向.但我得到任何错误消息.

Bal*_*usC 8

Faces消息是请求范围.重定向基本上指示webbrowser发送全新的HTTP请求(这也是您在浏览器地址栏中看到URL被更改的原因).在新请求中,当前在先前请求中设置的面部消息当然不可用.

有几种方法可以让它工作:

  1. 不要发送重定向.发送前进代替.你可以做到ExternalContext#dispatch()

    FacesContext.getCurrentInstance().getExternalContext().dispatch("error.xhtml");
    
    Run Code Online (Sandbox Code Playgroud)

    或者如果你已经在一个动作方法中,只需按常规方式导航

    return "error";
    
    Run Code Online (Sandbox Code Playgroud)
  2. 创建一个公共错误页面主模板,并为每种类型的错误使用单独的模板客户端,并将该消息放入视图中.

    <ui:composition template="/WEB-INF/templates/error.xhtml"
        xmlns="http://www.w3.org/1999/xhtml"
        xmlns:ui="http://java.sun.com/jsf/facelets"
    >
        <ui:define name="message">
            You must login to continue.
        </ui:define>
    </ui:composition>
    
    Run Code Online (Sandbox Code Playgroud)

    然后你可以像这样重定向到这个特定的错误页面redirect("error-login.xhtml").

  3. 通过重定向URL将一些错误标识符作为请求参数传递,redirect("error.xhtml?type=login")并让视图处理它.

    <h:outputText value="You must login to continue." rendered="#{param.type == 'login'}" />
    
    Run Code Online (Sandbox Code Playgroud)
  4. 将面部消息保留在闪存范围中.

    externalContext.getFlash().setKeepMessages(true);
    
    Run Code Online (Sandbox Code Playgroud)

    然而,Mojarra有一个有点错误的闪存范围实现.对于当前版本,当您需要重定向到其他文件夹时,这将不起作用,但当目标页面位于同一文件夹中时它将起作用.

  • 显然,调用链中更下游的一些其他代码也在调用“sendRedirect()”(或“externalContext.redirect()”,它在幕后委托给完全相同的方法)。您需要跳过该呼叫。另请参阅此相关答案以获取一些提示:http://stackoverflow.com/questions/2123514/java-lang-illegalstateexception-cannot-forward-after-response-has-been-committe/2125045#2125045 (2认同)