I can display an error/info message when a button is clicked using JSF, but I can't display a message when a page is loaded.
Please try the following.
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>
</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>
MessageController.java:
@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;
}
}
Every message is displayed correctly except for one message that is created by a constructor.
I want to display the message Managed Bean Initialized
when the page is loaded.