Java Reference
In-Depth Information
public void setLocale(Locale locale) { }
}
Being in an extension package, the type converter will automatically be
loaded. Just like that, we have support for the Contact class, as shown
in Figure 5.5 , on the following page.
The ContactFormatter 's task of returning a String from a Contact is very
simple:
Download email_07/src/stripesbook/ext/ContactFormatter.java
package stripesbook.ext;
public class ContactFormatter implements Formatter<Contact> {
public String format(Contact contact) {
return String.valueOf(contact.getId());
}
public void init() { }
public void setLocale(Locale locale) { }
public void setFormatType(String type) { }
public void setFormatPattern(String pattern) { }
}
We can now work directly with Contact objects in action beans and
JSPs, with the logic of going from String to Contact and back to String
being encapsulated in the type converter and formatter.
Using Constructor and toString
We've seen how Stripes type converters and formatters give us a place
for the code that converts a String to T and back to String . Using type
converters keeps the logic separate from the T class and enables us to
use Stripes validation errors. Formatters are powerful because we can
define different format types and patterns and easily format according
to the user's locale.
Despite all these advantages, sometimes we need only the bare mini-
mum for a data type.
I'll let you in on a dirty little secret. If Stripes doesn't find a type con-
verter for a type T —either built-in, specified in @Validate(converter=) , or
located in an extension package—it tries one last resort. If a T(String)
constructor is defined in the class T , Stripes uses it to create an instance
of T , passing the input as a parameter to the constructor.
So, to get type conversion and formatting with the least amount of code,
we can use a constructor that accepts one argument of type String for
type conversion and the toString ( ) method for formatting, both directly
in the model class.
 
 
Search WWH ::




Custom Search