jsf-2 - 通过消息传递的JSF通用错误屏幕

标签 jsf-2 error-handling resourcebundle forward dispatch

我有一个jsf应用程序,在其中我在@PostConstruct方法中执行了一些代码:

@PostConstruct
public void init() {
    try {
        // Do some form preparation
    } catch (Exception e) {
        try {
            FacesContext.getCurrentInstance().getExternalContext().dispatch("error.faces");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }


}

而且我有这个错误。xhtml:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" xmlns:p="http://primefaces.org/ui" template="/templates/main.xhtml">
    <ui:define name="title">
        <title>#{msg['page.title']}</title>
    </ui:define>
    <ui:define name="body">
        #{msg['global.error']}
    </ui:define>
</ui:composition>

现在我希望“global.error”和“page.title”作为资源束不是静态的,相反,我应该在发布构造中的某个地方传递我想要的消息,以便error.xhtml可以读取和显示,原因是这是所有屏幕都应引用此屏幕,因此搜索屏幕可以显示“搜索时出错”,而另一个屏幕可以显示“获取数据时出错”或“您请求的用户在我们的系统中不存在”

最佳答案

您可以使用#{flash}实现功能:

@PostConstruct
public void init() {
    try {
        // Do some form preparation
    } catch (Exception e) {
        try {
            FacesContext.getCurrentInstance().getExternalContext().getFlash().put("title", "Custom title");
            FacesContext.getCurrentInstance().getExternalContext().getFlash().put("error", "Custom error description");
            FacesContext.getCurrentInstance().getExternalContext().dispatch("error.faces");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

与 View :
<ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" xmlns:p="http://primefaces.org/ui" template="/templates/main.xhtml">
    <ui:define name="title">
        <title>#{flash['title']}</title>
    </ui:define>
    <ui:define name="body">
        #{flash['error']}
    </ui:define>
</ui:composition>

这种方法在进行重定向的同时也将起作用。

或者,您也可以将两个消息都作为字段来填充Bean,并将其附加为请求属性(如果您要进行转发),并以通常的方式在错误 View 中对其进行访问。

关于jsf-2 - 通过消息传递的JSF通用错误屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16880908/

相关文章:

jsf-2 - 警告 : This page calls for XML namespace declared with prefix [HTML element name] but no taglibrary exists for that namespace

pdf - 无法以p :media generated from streamed content in Primefaces显示PDF

jsf-2 - DefaultInstanceManager无法访问带有修饰符 ""的类的成员

javascript - Javascript 中 'nested' try/catch 语句的困惑

python - TypeError : list indices must be integers or slices, not str when parsing lists

java - 带扩展名的 ResourceBundle 完全限定名称

javascript - 如何解决与 primefaces jquery 的冲突

PHP自定义错误页面

java - 如何格式化资源包值以 HTML 格式显示

symfony - fatal error 异常: Error: Class 'ResourceBundle' not found