【问题标题】:JSF Generic error screen with message passed消息传递的 JSF 通用错误屏幕
【发布时间】:2013-05-28 16:03:59
【问题描述】:

我有一个 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();
        }
    }


}

我有这个error.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”不作为资源包是静态的,而是应该在 post 构造中的某个位置传递我想要的消息,以便 error.xhtml 可以读取和显示,这样做的原因是这个屏幕应该从所有屏幕中引用,所以一个搜索屏幕可以显示“搜索时出错”,另一个屏幕可以显示“获取数据时出错”或“您请求的用户在我们的系统中不存在"

【问题讨论】:

    标签: jsf-2 error-handling resourcebundle forward dispatch


    【解决方案1】:

    您可以使用#{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();
            }
        }
    }
    

    有视图:

    <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,并将其作为请求属性附加,然后在错误视图中以通常的方式访问它。

    【讨论】:

    • 你的解决方案听起来不错,我就是这样解决的:FacesContext.getCurrentInstance().getExternalContext().dispatch("error.faces?message=error.loading.screen");你觉得呢??
    • IMO 我认为将错误 ID 作为查询参数传递不是一个好主意,尤其是在有更清晰的解决方案的情况下。
    • 好吧,我还没有读到关于 flash 对象的信息,但因为它是更清洁的解决方案,所以我会去的
    • 这是您的项目,由您决定。但请确保在一个主题上:绝对值得阅读有关 flash 对象的内容。
    • 但我没有使用重定向,而是使用了 dispatch
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 2022-01-07
    • 2013-08-15
    • 2017-07-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多