Java Reference
In-Depth Information
To make sure
TimeTypeConverter
is not an automatically loaded exten-
sion, either it can be in a different package than an extension package,
such as the
stripesbook.opt
package used earlier, or it can be in an exten-
sion package and annotated with
@DontAutoLoad
. We can now use
Time-
TypeConverter
only on demand by annotating the property associated
with the time field:
@Validate(converter=TimeTypeConverter.
class
)
private
Date time;
Using a Type Converter and Formatter to Load Model Objects
A great way of using type converters and formatters is to load model
objects. Right now
Contact
objects are loaded from the contact DAO
using the contact's ID. This works fine but requires separate
contactId
and
contact
properties in the action bean.
The
contactId
property can be removed by implementing a type con-
verter that takes the contact ID as an input and returns the corre-
sponding
Contact
object with help from the contact DAO. With a for-
matter that does the opposite—takes a
Contact
object and returns the
contact ID—the
Contact
type can then be used directly, and JSPs can
use a
contact
parameter as follows:
<s:param name="contact" value="${contact}"/>
The
ContactTypeConverter
uses the
String
input as a contact ID and calls
ContactDao
to return the corresponding
Contact
object:
package
stripesbook.ext;
public class
ContactTypeConverter
implements
TypeConverter<Contact> {
private
ContactDao contactDao = MockContactDao.getInstance();
public
Contact convert(String string,
Class<?
extends
Contact> type,
Collection<ValidationError> errors)
{
try
{
return
contactDao.read(
new
Integer(string));
}
catch
(Exception exc) {
errors.add(
new
SimpleError(
"The contact ID {1} is not valid."));
return null
;
}
}
Search WWH ::
Custom Search