I recently discovered that Struts is able to format strings in a most convenient way. Say you have some bean class (ie. Order) in your application and wants to print the attribute values of an instance of that class (ie. orderObj) in a .jsp page. To do this, you set the class instance as either a request or session attribute and use the struts bean taglib to write out the attribute values:
Order
Date:
<bean:write name=
"orderObj" property=
"orderDate"/>
Now, when struts write out these attributes values, each value is converted to a java.lang.String using the toString() method of the attribute class. So if the OrderClass.orderDate attribute is of type java.util.Date, the following output will be generated:
Order Date:
Mon Apr 12 10:30:10 CST 2004
Which is in the default format (dow mon dd hh:mm:ss zzz yyyy) used by the java.util.Date.toString() method.
Often, however, it is nice to be able to use a custom date (or time) format for printing time stamps. J2SE offers the java.text.SimpleDateFormat class for formatting dates, but using an instance of this class quickly becomes tiresome: The nice thing about the default output is, that it is specific to the brower's locale settings; to maintain this aspect, the SimpleDateFormat instance must either be available on every .jsp page, or have the client locale included with every format request (if not, the formatting will be based upon server locale).
Luckily, the struts bean taglib enables this sort of customization - it just took me a while to discover it :)
Here's how:
The <bean:write> tag used above can include formatting information, by using either the format or formatKey properties. Using the format property, a custom format can be stated directly:
Order
Date:
<bean:write name=
"orderObj" property=
"orderDate" format=
"EEE, MMM d, 'yy"/>
Will generate:
Order
Date:
Mon, Apr
12,
'04
Please see the J2SE API spcification for information on format strings. If you want to different formats for different locales, you can use the formatKey property, which refers to an application resource bundle (see this for information on using message resources with struts). In the message property file(s), you define the locale specific formats:
In resources.properties (default locale):
…
format.date.short=MM-dd-yyyy
format.date.long=EEEEE, MMMMM d. ' @'HH:mm
…
In resources_da.properties (another locale):
…
format.date.short=dd-MM-yyyy
format.date.long=EEEEE 'd.' d. MMMMM ' kl.' HH:mm
…
The formats are then used in the bean tags:
Order
Date:
<bean:write name=
"orderObj" property=
"orderDate" formatKey=
"format.date.long"/>
Which will generate output based upon the given format and the browser's locale:
Order Date:
Monday, April 12. @10:30
Which is nice….
If you enjoyed this post, make sure you subscribe to my RSS feed!