Another approach, you can make use of FacesMessage
here which you add to the context using FacesContext#addMessage()
. FacesMessages are request based and likely more suited for the particular functional requirement than some custom messaging approach.
Here's an example of the bean action method:
public void sendMail() {
FacesMessage message;
try {
Mailer.send(from, to, subject, message);
message = new FacesMessage("Mail successfully sent!");
} catch (MailException e) {
message = new FacesMessage("Sending mail failed!");
logger.error("Sending mail failed!", e); // Yes, you need to know about it as well! ;)
}
FacesContext.getCurrentInstance().addMessage(null, message);
}
With a null
clientId the message becomes "global", so that you can make use of the following construct to display only global messages:
<h:messages globalOnly="true" />
Update: to have the success and error message displayed in a different style, play with the FacesMessage.Severity
:
message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Mail successfully sent!", null);
} catch (MailException e) {
message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Sending mail failed!", null);
.. in combination with infoClass/infoStyle
and errorClass/errorStyle
in h:messages
:
<h:messages globalOnly="true" infoStyle="color:green" errorStyle="color:red" />