系統比較 Struts 2 三種資料封裝模式(屬性驅動、模型驅動、ActionForm 風格),闡述聲明式異常處理配置與異常資訊輸出,並詳細對比 Struts 1/2 類型轉換器註冊機制差異。
Action 直接定義屬性封裝請求參數與處理結果,最簡單直接。
Action 實作 ModelDriven<T> 介面,getModel() 返回模型實例:
public class LoginAction implements Action, ModelDriven<UserBean> {
UserBean model = new UserBean();
public UserBean getModel() { return model; }
}
ModelDrivenInterceptor)<s:property value="model.username"/><s:property value="username"/> 也會智能輸出模型屬性Struts 2 亦支援專門 POJO 處理表單,但模型驅動更純粹。
思維同 Struts 1,在 struts.xml 配置:
<global-exception-mappings> 對應 Struts 1 <global-exceptions><exception-mapping> 對應 Struts 1 <exception>Action execute() 僅需 throws Exception,框架自動處理轉向。
<s:property value="exception"/>:異常物件本身<s:property value="exceptionStack"/>:異常堆疊資訊(Struts 1 無此功能)<s:property value="exception.message"/>:異常 message 屬性若 execute() throw new Exception("name.error"),輸出對應訊息:
<s:property value="%{getText(exception.message)}"/>
找不到對應鍵時直接輸出原鍵值 "name.error"。
提供 ActionName-conversion.properties 放在 Action 同包目錄:
user=com.unmi.struts2.converter.UserConverter
user 為 Action 屬性名,多行對應多屬性。
提供 xwork-conversion.properties 放在 classpath(WEB-INF/classes):
com.unmi.vo.User=com.unmi.struts2.converter.UserConverter
鍵為屬性類型,遇到該類型屬性自動使用。多行對應多類型。
ConvertUtils.register(new DateConverter(), Date.class);
Struts 2 以配置檔替代代碼,支援局部註冊,更靈活。