当页面加载JSF时,如何显示消息?
我可以在使用JSF单击按钮时显示错误/信息消息,但在加载页面时无法显示消息 请尝试以下方法 index.xhtml:当页面加载JSF时,如何显示消息?,jsf,Jsf,我可以在使用JSF单击按钮时显示错误/信息消息,但在加载页面时无法显示消息 请尝试以下方法 index.xhtml: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html"> <h:head> <title>Facelet Title</title> &
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<h:form id="componentForm">
<h:messages errorStyle="color: red" infoStyle="color: green" globalOnly="true" />
Enter the word Java here:
<h:inputText id="javaText" value="#{messageController.javaText}" />
<h:message for="javaText" errorStyle="color: red" infoStyle="color: green" />
<h:commandButton id="addMessage" action="#{messageController.newMessage}"
value="New Message" />
</h:form>
</h:body>
</html>
除一条由构造函数创建的消息外,所有消息均正确显示
我想在加载页面时显示消息
managedbeaninitialized
。我遇到了同样的问题,不幸的是,页面加载时FacesContext only init
因此,在页面初始化时,不能使用FacesContext.getCurrentInstance().addMessage():(
我尝试了两种解决方案
- 文档准备就绪后,调用ajax显示消息
- 传递字符串消息并显示它
@Named(value = "messageController")
@SessionScoped
public class MessageController implements Serializable {
int hitCounter = 0;
private String javaText;
public MessageController() {
javaText = null;
FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Managed Bean Initialized", null);
FacesContext.getCurrentInstance().addMessage(null, facesMsg);
}
public void newMessage() {
String hitMessage = null;
hitCounter++;
if (hitCounter > 1) {
hitMessage = hitCounter + " times";
} else {
hitMessage = hitCounter + " time";
}
Date currDate = new Date();
FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "You've pressed that button " + hitMessage + "! The current date and time: " + currDate, null);
FacesContext.getCurrentInstance().addMessage(null, facesMsg);
if (getJavaText().equalsIgnoreCase("java")) {
FacesMessage javaTextMsg = new
FacesMessage(FacesMessage.SEVERITY_INFO, "Good Job, that is the correct text!", null);
FacesContext.getCurrentInstance()
.addMessage("componentForm:javaText", javaTextMsg);
} else {
FacesMessage javaTextMsg = new
FacesMessage(FacesMessage.SEVERITY_ERROR, "Sorry, that is NOT the correct text!", null);
FacesContext.getCurrentInstance()
.addMessage("componentForm:javaText", javaTextMsg);
}
}
public String getJavaText() {
return javaText;
}
public void setJavaText(String javaText) {
this.javaText = javaText;
}
}