Java 在构造函数或@PostConstruct方法中设置消息-可能吗?
是否可以在托管Bean的构造函数或@PostConstruct方法中设置消息 例如:Java 在构造函数或@PostConstruct方法中设置消息-可能吗?,java,jsf,jsf-2,facelets,Java,Jsf,Jsf 2,Facelets,是否可以在托管Bean的构造函数或@PostConstruct方法中设置消息 例如: public class Example { @ManagedProperty(value = "#{index.facade}") private PersistenceFacade pf; public Example() { } @PostConstruct public void doExample() { try {
public class Example {
@ManagedProperty(value = "#{index.facade}")
private PersistenceFacade pf;
public Example() {
}
@PostConstruct
public void doExample() {
try {
pf.disconnect();
((HttpSession) FacesContext.getCurrentInstance()
.getExternalContext().getSession(false)).invalidate();
setMessage("Successful.");
} catch (DAOException e) {
e.printStackTrace();
setMessage("Error: " + e.toString());
}
}
public void setPf(PersistenceFacade pf) {
this.pf = pf;
}
private void setMessage(String message) {
FacesMessage fm = new FacesMessage(message);
FacesContext.getCurrentInstance().addMessage(null, fm);
}
public String back() {
return "/index.xhtml";
}
example.xhtml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>Example</title>
</h:head>
<h:body>
<h1>
<h:outputText value="Example" />
</h1>
<h:form>
<p>
<h:commandButton id="back" value="Back"
action="#{example.back}"></h:commandButton>
</p>
<h:messages globalOnly="true" />
</h:form>
</h:body>
</html>
<h:messages globalOnly="true" rendered="#{!empty example.fm}" />
例子
我可以在Eclipse控制台中看到消息,但在页面上看不到,为什么?有什么方法可以通知用户结果吗?我发现,如果我以这种方式添加/更改托管Bean和XHTML文件,将显示消息: 在Example.java中:
private FacesMessage fm;
public FacesMessage getFm() {
return fm;
}
private void setMessage(String message) {
fm = new FacesMessage(message);
FacesContext.getCurrentInstance().addMessage(null, fm);
}
在example.xhtml中:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>Example</title>
</h:head>
<h:body>
<h1>
<h:outputText value="Example" />
</h1>
<h:form>
<p>
<h:commandButton id="back" value="Back"
action="#{example.back}"></h:commandButton>
</p>
<h:messages globalOnly="true" />
</h:form>
</h:body>
</html>
<h:messages globalOnly="true" rendered="#{!empty example.fm}" />
在放置h:消息之前,尝试放置一些访问JSFbean属性的EL
<h:outputText rendered="#{not empty bean.prop}" />
<h:messages id="msg" />
而不是像这样
<h:messages id="msg" />
<h:outputText rendered="#{not empty bean.prop}" />