Posted on 2008-01-08 21:31
Norvid 閱讀(228)
評(píng)論(0) 編輯 收藏
本來打算這個(gè)blog寫些關(guān)于腳本編程的內(nèi)容,可是最近一直在搞java的開發(fā),而且總被一些平時(shí)沒注意的問題“騷擾”。好吧,我承認(rèn),是我基礎(chǔ)不扎實(shí)……
比如說這個(gè)Struts的異常處理,雖然我是知道能根據(jù)異常類的類型來導(dǎo)向相應(yīng)的頁面的,可是這樣很不好。于是我根據(jù)過往的各種經(jīng)驗(yàn)將Struts的使用總結(jié)為以下形式。
// execute純粹作為轉(zhuǎn)發(fā)器與異常捕捉與處理
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的默認(rèn)入口只是作為一個(gè)轉(zhuǎn)發(fā)器以及異常捕獲點(diǎn)進(jìn)行相關(guān)的異常處理(見error函數(shù))。真正的處理改為由各個(gè)功能函數(shù)來處理(如list函數(shù))。呵呵,是不是很像DispatchAction類?就是從它想出來的。如果直接使用DispatchAction類的話,每個(gè)方法都要自己寫異常處理,太繁瑣了。弄個(gè)轉(zhuǎn)發(fā)器只需寫一次就行了。
呀,有點(diǎn)跑題了。其實(shí)我也就想說其實(shí)可以使用web.xml的配置來根據(jù)不同的http異常來導(dǎo)向不同的頁面……雖然如果注意的話,異常都會(huì)在struts的Action層就能完全捕獲住了(屬于開發(fā)階段中的JSP錯(cuò)誤除外)。
web.xml中配置HTTP異常的方法為:
<!-- 根據(jù)錯(cuò)誤碼進(jìn)行跳轉(zhuǎn)-->
<error-page>
<error-code>500</error-code>
<location>/error.jsp</location>
</error-page>