background image

The getMessage Method

<< Implementing the Validator Interface | JavaServer Faces Application >>
<< Implementing the Validator Interface | JavaServer Faces Application >>

The getMessage Method

if (valid) {
break;
}
}
if ( !valid ) {
FacesMessage errMsg =
MessageFactory.getMessage(context,
FORMAT_INVALID_MESSAGE_ID,
(new Object[] {formatPatterns}));
throw new ValidatorException(errMsg);
}
}
This method gets the local value of the component and converts it to a String. It then iterates
over the formatPatternsList list, which is the list of acceptable patterns as specified in the
formatPatterns
attribute of the custom validator tag.
While iterating over the list, this method checks the pattern of the component's local value
against the patterns in the list. If the pattern of the local value does not match any pattern in the
list, this method generates an error message. It then passes the message to the constructor of
ValidatorException
. Eventually the message is queued onto the FacesContext instance so
that the message is displayed on the page during the render response phase.
The error messages are retrieved from the Application instance by MessageFactory. An
application that creates its own custom messages must provide a class, such as MessageFactory,
that retrieves the messages from the Application instance. When creating your own
application, you can simply copy the MessageFactory class from the Duke's Bookstore
application to your application.
The getMessage(FacesContext, String, Object) method of MessageFactory takes a
FacesContext
, a static String that represents the key into the Properties file, and the format
pattern as an Object. The key corresponds to the static message ID in the FormatValidator
class:
public static final String FORMAT_INVALID_MESSAGE_ID =
"FormatInvalid";
}
When the error message is displayed, the format pattern will be substituted for the {0} in the
error message, which, in English, is
Input must match one of the following patterns {0}
JavaServer Faces applications can save the state of validators and components on either the
client or the server.
"Specifying Where State Is Saved" on page 462
explains how to configure
your application to save state on either the client or the server.
Creating a Custom Validator
The Java EE 5 Tutorial · September 2007
400