下午搞了一下Struts處理異常的框架,不錯,確實很好用,可以省很多事,閑話暫且不表,進入正題
首先新建一個項目,然后要做的第一步當然是——添加Struts支持啦~~呵呵。
找到struts-config.xml文件,如果想配置全局異常處理,則需要在<global-exceptions></global-exceptions>之間設置,如果只想單獨為某個Action設置其異常處理,則將設置寫在<action></action>之間即可,具體配置很簡單,代碼如下:

Code
<exception
key="unLogin"<!--對應資源文件中的key,用于錯誤顯示-->
path="/index.jsp"<!--出錯了程序會跳到哪里去
.-->
type="java.lang.Exception" <!--捕獲異常的類型-->/>
接下來測試一下吧,寫一個登陸頁面,提交到某個action里面,當用戶名為空時拋出Exception,當然你也可以編寫自己的Exception類,然后在配置文件中作相應的修改就可以了。
index.jsp代碼如下:

Code
<%@ page language="java" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %>
<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html:html lang="true">
<head>
<html:base />
<title>index.jsp</title>
</head>
<body><html:errors/>
<html:form action="/login" method="post" focus="login">
<table border="0">
<tr>
<td>Login:</td>
<td><html:text property="username" /></td>
</tr>
<tr>
<td>Password:</td>
<td><html:password property="password" /></td>
</tr>
<tr>
<td colspan="2" align="center"><html:submit /></td>
</tr>
</table>
</html:form>
</body>
</html:html>
loginAction代碼如下:

Code
/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.lc.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.lc.LoginForm;
/**
* MyEclipse Struts
* Creation date: 07-30-2008
*
* XDoclet definition:
* @struts.action path="/login" name="loginForm" input="/form/login.jsp" scope="request" validate="true"
* @struts.action-exception key="unLogin" path="/index.jsp"
*/
public class LoginAction extends Action {
/*
* Generated Methods
*/
/**
* Method execute
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
* @throws Exception
*/
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
LoginForm loginForm = (LoginForm) form;// TODO Auto-generated method stub
if(loginForm.getUsername()==null||loginForm.getUsername().equals("")){
throw new Exception();
}
return mapping.findForward("login");
}
}
接下來測試一下吧,異常被捕獲了,login.do被重定向到了index.jsp中去,測試結束。
雖然這是一個很小的例子,但是足以感覺到運用到實際中可以省很多事,項目中異常的處理不再需要無數個try/catch塊組合,只需要在xml文件中進行簡單設置即可。
文章來源:
http://www.cnblogs.com/xiaoao808/archive/2008/07/30/1256650.html
posted on 2008-07-30 17:15
破名超難起 閱讀(98)
評論(0) 編輯 收藏