background image

JavaServer Faces Application

<< The getMessage Method | Creating a Custom Tag >>
<< The getMessage Method | Creating a Custom Tag >>

JavaServer Faces Application

If your JavaServer Faces application saves state on the client (which is the default), you need to
make the Validator implementation implement StateHolder as well as Validator. In
addition to implementing StateHolder, the Validator implementation needs to implement
the saveState(FacesContext) and restoreState(FacesContext, Object) methods of
StateHolder
. With these methods, the Validator implementation tells the JavaServer Faces
implementation which attributes of the Validator implementation to save and restore across
multiple requests.
To save a set of values, you must implement the saveState(FacesContext) method. This
method is called during the render response phase, during which the state of the response is
saved for processing on subsequent requests. When implementing the
saveState(FacesContext)
method, you need to create an array of objects and add the values of
the attributes you want to save to the array. Here is the saveState(FacesContext) method
from FormatValidator:
public Object saveState(FacesContext context) {
Object values[] = new Object[2];
values[0] = formatPatterns;
values[1] = formatPatternsList;
return (values);
}
To restore the state saved with the saveState(FacesContext) method in preparation for the
next postback, the Validator implementation implements restoreState(FacesContext,
Object)
. The restoreState(FacesContext, Object) method takes the FacesContext
instance and an Object instance, which represents the array that is holding the state for the
Validator
implementation. This method sets the Validator implementation's properties to
the values saved in the Object array. Here is the restoreState(FacesContext, Object)
method from FormatValidator:
public void restoreState(FacesContext context, Object state) {
Object values[] = (Object[]) state;
formatPatterns = (String) values[0];
formatPatternsList = (ArrayList) values[1];
}
As part of implementing StateHolder, the custom Validator implementation must also
override the isTransient and setTransient(boolean) methods of StateHolder. By default,
transientValue
is false, which means that the Validator implementation will have its state
information saved and restored. Here are the isTransient and setTransient(boolean)
methods of FormatValidator:
private boolean transientValue = false;
public boolean isTransient() {
return (this.transientValue);
Creating a Custom Validator
Chapter 12 · Developing with JavaServer Faces Technology
401