Struts 1 Tips

Property Naming Rule (命名規則)

如果沒有依照Java Naming Convension, 使用 X_XXX 這種 Property 命名方式(全大寫), 會因為不熟悉JavaBean對Property的解析規則, 導致對不到相對應的 Get method, 出現 “No getter method for property…” 的錯誤。

例如:

有一個 getN_CODE() 的 method, 如果這樣抓值

<bean:write name=”element” property=”N_CODE”/>

會出Exception。

主要原因為JavaBean對Property命名的解析規則

“8.8 Capitalization of inferred names.

……Thus when we extract a property or event name from the middle of an existing Java name, we normally convert the first character to lower case. However to support the occasional use of all upper-case names, we check if the first two characters of the name are both upper case and if so leave it alone….” – from JavaBeans Spec

因此

getFirstName → firstName

getFName → FName (前兩個字母大寫, 因此不做轉換)

getN_CODE → n_CODE (非前兩個字母大寫, 因此使用一般轉換, 將第一個字轉成小寫)

要改成

<bean:write name=”element” property=”n_CODE”/>

才正確。

另外

getnCode → nCode (小寫, 不做轉換)

bean:write 的限制

如果為非字串型態, 必須指定格式, 否則會出現 “Cannot find message resources under key org.apache.struts.action.MESSAGE…” 的錯誤

例如 rowNum 為數字型態

<bean:write name=”element” property=”rowNum”/>

會出錯, 需加上 format

<bean:write name=”element” property=”rowNum” format=”#”/>

日期型態要用日期 format

<bean:write name=”element” property=”createDate” format=”yyyy/MM/dd”/>

Nested Iterator (nested:iterate)

(MyBean)
  private String name;
  private List<MyBean> subBeans = new ArrayList<MyBean>();
  ...

(MyForm)
  private List<MyBean> mainBeans = new ArrayList<MyBean>();
  ...

(JSP)
<nested:iterate id="lvl1" name="myForm" property="mainBeans">
  <nested:write name="lvl1" property="name"/>
  ...
  <nested:iterate id="lvl2" name="lvl1" property="subBeans">
    <nested:write name="lvl2" property="name"/>
    ...
  </nested:iterate>
</nested:iterate>

如果出現 No Collection Found 的 Exception, 表示 iterate 的物件是 NULL, 因此需先用<nested:notEmpty…>判斷才可進行nested:iterate

Reference: http://struts.apache.org/release/1.2.x/userGuide/struts-nested.html

Dynamic Radio Buttons

http://www.ibm.com/developerworks/library/j-sr4/

Validator

1. strauts-config.xml增加plug-in資訊

<plug-in className="org.apache.struts.validator.ValidatorPlugIn" >
 <set-property property="pathnames"
 value="/WEB-INF/validator-rules.xml, /WEB-INF/validator-user.xml"/>
</plug-in>

2. validation.xml, validator-rules.xml等檔案的DOCTYPE中dtd的版本必需與commons-validator.jar的版本一致, 否則會出現dtd找不到的Exception

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s