Thursday, March 5, 2009

Formatting Numbers with Struts 2

I just wasted about 4 hours trying to figure out how you can format a number in a textfield with Struts 2. The only explanation was at http://struts.apache.org/2.0.14/docs/formatting-dates-and-numbers.html
I found was to make my <s:textfield> tag look like this:


<s:textfield key="orderItem.price"
value="%{getText('format.number',{'orderItem.price'})}" />

In this instance format.number refers to an entry in your package.properties file (NOTE: You actually should call this file package.properties. 'package' does not refer to the actual name of your package.) Inside this package.properties file you need an entry that looks similar to this

format.number= USD{0,number,##0.00}

which will output the number 1500.0 like: USD 1500.00

Anywho, there are several ways to define a formatting properties file, but for eases sake, just place the package.properties file inside the directory that your java action is. If I have an action org.james.actions.ViewPurchaseOrdersAction.java. Then my package.properties file would belong in org.james.actions. Now if you want your package.properties file to apply to all your actions, you can adjust the placement of the file, placing it higher in the package hierarchy. Basically Struts 2 will hunt down your package.properties file for you. The choices you make all depends on how tied to your actions your formatting should be.

Back on track. The key attribute of the above tag does something that I'm too lazy to look up. I didn't need it, we'll pass over. The shady thing though, is the value attribute. Using the above style for the value attribute, I was not able to get my formatted price to display.

After exhausting my patience trying all kinds of different things I started trying random things, and eventually got the following to work (Notice that the % and quotes are not inside the purchaseOrder.amount argument):

<s:textfield name="amount" theme="simple" value="%{getText('format.number',{orderItem.price})}" />

I'm not sure if this is because I'm on Struts 2.1, while the tutorial I took that snippet from is Struts 2.0, whether I just implemented something improperly, or whether that code snippet is just flat out wrong.

Either way I don't really care. My code works now, and I can move onto the next problem.
If the Struts 2 example from the official site isn't working for you, try mine.





No comments:

Post a Comment