Posted on 2008-01-08 21:31
Norvid 閱讀(225)
評論(0) 編輯 收藏
本來打算這個blog寫些關于腳本編程的內容,可是最近一直在搞java的開發,而且總被一些平時沒注意的問題“騷擾”。好吧,我承認,是我基礎不扎實……
比如說這個Struts的異常處理,雖然我是知道能根據異常類的類型來導向相應的頁面的,可是這樣很不好。于是我根據過往的各種經驗將Struts的使用總結為以下形式。
// execute純粹作為轉發器與異常捕捉與處理
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
try {
String method = request.getParameter("method");
if (StringUtils.isEmpty(method) || method.equalsIgnoreCase("query")) {
return query(mapping, form, request, response);
} else if (method.equalsIgnoreCase("list")) {
return list(mapping, form, request, response);
} else if (method.equalsIgnoreCase("info")) {
return info(mapping, form, request, response);
} else {
return query(mapping, form, request, response);
}
} catch (Exception error) {
return error(mapping, form, request, response, error);
}
}
/**
* 異常捕獲
*/
private ActionForward error(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response,
Exception error) {
logger.error("error: " + error.getMessage());
request.setAttribute("msg", error.getMessage());
request.setAttribute("error", error);
return mapping.findForward("error");
}
/**
* 全部查詢
*/
private ActionForward list(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {


return mapping.findForward("query");
}


如上面的代碼所示,action的默認入口只是作為一個轉發器以及異常捕獲點進行相關的異常處理(見error函數)。真正的處理改為由各個功能函數來處理(如list函數)。呵呵,是不是很像DispatchAction類?就是從它想出來的。如果直接使用DispatchAction類的話,每個方法都要自己寫異常處理,太繁瑣了。弄個轉發器只需寫一次就行了。
呀,有點跑題了。其實我也就想說其實可以使用web.xml的配置來根據不同的http異常來導向不同的頁面……雖然如果注意的話,異常都會在struts的Action層就能完全捕獲住了(屬于開發階段中的JSP錯誤除外)。
web.xml中配置HTTP異常的方法為:
<!-- 根據錯誤碼進行跳轉-->
<error-page>
<error-code>500</error-code>
<location>/error.jsp</location>
</error-page>