JSF Error Messages

Created: 28.07.2014

JSF Error Messages with FacesMessages

Error messages are used to provide the users of your web application feedback about dialogs, access rights, the state of a process and much more. JSF includes a mechanism to display such messages. Entity classes use this mechanism, for instance, to display validation errors within tags.

Prepare a FacesMessage in a Handler

Assume there is a RegistrationHandler to register new users in a (very) simple web application:

public class RegistrationHandler {
	private String userName;
	private String firstPassword;
	private String secondPassword;

	public String register() {
		if (!firstPassword.equals(secondPassword)) {
			FacesContext facesContext = FacesContext.getCurrentInstance();
			FacesMessage facesMessage = new FacesMessage("The provided passwords don't match!");
			facesContext.addMessage("registerMessage", facesMessage);

			return null;
		} else {
			return "success.xhtml?faces-redirect=true";
	//omitted get/set methods

The handler makes sure the provided passwords match before he allows a user to register himself (registration itself is omitted in this example). If the passwords don’t match it creates an error message to notify the user. The message is sent to a JSF component with the id=”registerMessage”.
In addition you can set a severity level. In this case the severity level “error” is set.

Display the Message in a View

To display the message a element with the id=”registerMessage” must exist:

		<h:panelGrid columns="2">
			<h:outputText for="nameInput" value="Name" />
			<h:inputText id="nameInput" value="#{registrationHandler.userName}" />

			<h:outputText for="firstPasswordInput" value="Password" />
			<h:inputText id="firstPasswordInput" value="#{registrationHandler.firstPassword}" />

			<h:outputText for="secondPasswordInput" value="Repeat password" />
			<h:inputText id="secondPasswordInput" value="#{registrationHandler.secondPassword}" />
		<h:commandButton value="Register"
			action="#{registrationHandler.register()}" />
		<h:messages id="registerMessage" errorClass="errorMessageBox"/>

Setting the Appearence of FacesMessages

The element is designed to display several messages in a list (you can also pick table layout).
You can set different styles for each severity level to format the message box. For example consider the following style sheet which leads to the output shown below:

	background-color: #FFCEC2;
	border: 1px solid #800000;
	padding: 20px;
	margin: 20px 0px;
	border-radius: 4px;
	list-style-type: none;

The result will look like this: