Struts bean:write format attribute

I absolutely love the format and formatKey attributes of bean:write tag in Struts framework. You can use these attributes to format the display of your form bean properties. This works pretty well in displaying currency and date/time values. For example, you can display 1234.567 as $1,234.57 and 08/12/2006 as Aug 12, 2006. Here is how it works:
 


<bean:write name="myForm" property="amount" format="$#,000.00" />

OR

<bean:write name="myForm" property="amount" formatKey="myapp.currency.format" />

AND

myapp.currency.format=$#,000.00 (in resource bundle)



 
The preferred way is to use the second format because it makes the code portable. Plus, if you want to change the format, you can make the change in resource bundle without having to worry about changing all your JSPs.
 
So far so good. When I tried to use this feature in one of my recent projects, it didn't work! Why? Because the type of the property being formatted cannot be String. The format attribute simply uses default format (display the property as is) when the property is of type java.lang.String. In other words,
private double amount; // will be formatted correctly
private String amount; // will NOT be formatted at all
 
This could be a feature or a limitation but I haven't been able to figure out why String shouldn't work! Why do I expect the format attribute to do the type conversion? Because the framework automatically does the type conversion on form submission. Here is what I mean by that:
 
// action form code
public class MyForm extends ActionForm{
private double amount;
}
 
// jsp code
<html:text name="myForm" property="amount" /> 
 
Even though request.getParameter("amount") returns a String, the framework happily converts the String to double. If this conversion is automatic, why can't it convert String to double and try to display the value in currency format in the format attribute? I am sure this has been raised/discussed/considered somewhere but I can't find it. If some one knows let me know.
 
There is another problem (not really a Struts problem though). There is no way to format phone numbers. If you get a String 8001234567 from the database and would like to convert to (800) 123-4567 OR 800-123-4567, currently there is no tag or attribute to do that (or I don't know about it). I was hoping, since it's so easy to format currency and date objects, it would be easy to format phone numbers but looks like it's my challenge to write something like that.

Struts 2 in Action
Practical Apache Struts 2 Web 2.0 Projects (Practical Projects)Struts: The Complete Reference, 2nd Edition (Complete Reference Series)

0 comments: