Stripes' philosophy when it comes to formatting is pretty simple:
- Formatting should be easy (duh)
- Formatting should occur on the page, not in the ActionBean or business code
- Formatting should be localized
- Formatting should be easy to extend
...
Now all that's left is implementing your own Formatter
class. This is a relatively simple operation. Remember that as your inputs you will receive an object to be formatted, a Locale
, a formatType
and a formatPattern
. You may choose to use, or ignore as many of these parameters as you see fit. The following is an example of a custom Formatter for formatting social security numbers:
Code Block | ||||
---|---|---|---|---|
| ||||
public class SsnFormatter implements Formatter<Ssn> { private String formatType; /** Sets the format type to be used to render Ssns as Strings. */ public void setFormatType(String formatType) { this.formatType = formatType; } public void setFormatPattern(String formatPattern) { // SsnFormatter doesn't use format-pattern } public void setLocale(Locale locale) { // Ssn's are US specific, so no locale support either } /** Sets defaults if a formatType was not supplied. */ public void init() { if (this.formatType == null) { this.formatType = "lastfour"; } } /** Formats the Ssn supplied as a String. */ public String format(Ssn ssn) { if ("lastfour".equals(this.formatType)) { return "###-##-" + ssn.getLastFourDigits(); } else if ("allnine".equals(this.formatType)) { return ssn.getDigits(0,3) + "-" + ssn.getDigits(3,5) + "-" + ssn.getLastFourDigits(); } } } |