我有一个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”不要像资源包那样是静态的,而是我应该在post构造中传递我想要的消息,以便error.xhtml可以读取和显示,这样做的原因是该屏幕应该从所有屏幕引用,因此搜索screne可以显示“搜索时出错”,另一个屏幕可以显示“获取数据时出错”或“您请求的用户不存在于我们的系统中“
答案 0 :(得分:0)
您可以使用#{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();
}
}
}
with 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并将其作为请求属性附加,如果您正在执行转发,并在错误视图中以通常的方式访问它。