A frequently asked question is how best to display dates and numbers
using a specified format. There are a number of approaches for this,
the most naive of which would be to add a method to your action class
to do the formatting for you. This method would take in a Date (or
subclass) object as a parameter, and return a formatted String.
最通用的方式是:給Action類添加一個方法來格式化?
That approach however suffers from a number of flaws. For example,
it is not i18n aware. The date format specified is rigid, and will not
adapt to different locales easily (assuming you're not using a default
formatter that is). It also clutters up your actions with code that has
nothing to do with the action itself.
指出添加Action中format方法的缺點n多
Instead, the recommended approach is to use Java's built-in date formatting features via use of the s:text tag.
所以,用s:text標簽才是王道
The s:text tag should be used for all i18n values. It will look up
the properties file for your action, and from that select the value for
the key that you specify. This is best illustrated in an example:
<!-- display the number of items in a cart -->
<s:text name="'cart.items'" value0="cartItems" />
The above tag will work as follows. value0 will result in a call to getCartItems() on your action class. The cart.items
name is escaped, so it is treated as a literal key into the actions'
properties file. Your MyAction.properties file will contain the
following:
cart.items=You have {0} items in your cart.
Normal Java MessageFormat behaviour will correctly substitute {0} with the value obtained from getCartItems.
Needless to say, this can get a lot more elaborate, with the ability
to specify both date and number formatting. Let us consider another
example. The goal here is to display a greeting to the user, as well as
the date of their last visit.
<s:text name="'last.visit'" value0="userName" value1="lastVisit(userName)" />
MyAction.java contains:
public String getUserName() { ... };
public Date getLastVisit(String userName) { ... };
Your MyAction.properties file will then contain:
last.visit=Welcome back {0}, your last visit was at {1,date,HH:mm dd-MM-yyyy}
As you can see, this is a very powerful mechanism and allows you to
easily display numbers and dates using any formatting rules that Java
allows.
正如你看到的,這是一個非常強大的機制,允許你容易第展示數字和日期,而且用特定的格式化方式.
Samuel說:在Struts2里,每個Action都可以對應一個資源文件,用s:text也是不錯地。就是教條了點,比如設定數字是money方式顯示的話在中國自然用¥,在美國自然是$,但這里,必須顯式地寫兩份資源文件里:一份美國:format.money = {0,number,$##0.00},另一份中國:format.money = {0,number,¥##0.00}
 |
value0 interface deprecated
The examples above pass in the values as:
<s:text name="'text.message'" value0="userName"/>
These values should now (>2.1.7?) be passed as params:
<s:text name="'text.message'"> <s:param value="'userName'"/> </s:text>
|
 |
Some message format examples
Here are some examples of formatting in the properties file:
format.date = {0,date,MM/dd/yy} format.time = {0,date,MM/dd/yy ha} format.percent = {0,number,##0.00'%'} format.money = {0,number,$##0.00}
|