Struts1.X异常处理 --作者:马庆槐 |
摘要:本文描述了在在Struts 1.X异常处理框架和流程,以实际项目开发异常处理事例讲解在项目中如何在Dao层使用异常处理机制,并给出在每个阶段内容。
1、概述
在Struts 1.X中对异常的处理使用ExceptionHandler,一旦出现已经定义的异常就会转到相应得页面,并且携带定制的信息。Struts框架提供了默认的异常处理org.apache.struts.action.ExceptionHandler,它的execute()方法负责处理异常。在需要实现自定义处理时重写此方法,可以在配置文件定义由谁来处理在Dao或者Action类中掷出的某种异常。
2、异常处理流程
Struts的控制器负责捕获各种异常,包括控制器运行中本身抛出的异常,以及调用模型的业务方法时抛出的异常。当Struts的控制器捕获到异常后,在异常处理代码块中,创建描述信息的ActionMessage对象把它保存在ActionMessages对象中,然后把ActionMessages保存在特定范围(配置文件中的scope)。然后可以用检索特定范围内的ActionMessages对象。
进行Struts 1.X 异常处理包括如下步骤:
- 定义自己的异常类
public class AppException extends RuntimeException - 定义异常处理类
public class AppExceptionHandler extends ExceptionHandler覆盖execute方法,处理自己的异常类,其它的异常由父类自己处理。
- 定义资源文件
在MessageResources.properties中定义需要在Dao中抛出异常时声明的内容。
- 配置struts-config.xml
配置公共异常处理文件<global-exceptions>,加入资源文件
<message-resources parameter="MessageResources" /> - 在Dao中抛出异常
在数据库操作层中抛出在资源文件中定义的异常。在数据库操作层抛出异常,是为了更好的捕获每一个增删改查操作具体异常内容。
- 公共异常处理页面
使用struts标签<html:errors/>进行异常信息显示。
3、异常处理具体内容
(1)定义自己的异常类
public class AppException extends RuntimeException { // 错误代码 private String errorCode; //资源文件中定义代码 private Object [] args; //填充资源文件中占位信息,如{0},{1}等 public AppException(String errorCode){ this.errorCode = errorCode; } public AppException(String errorCode, Object [] args){ this.errorCode = errorCode; this.args = args; } public AppException(String errorCode, String arg){ this(errorCode,new Object[]{arg}); } public Object[] getArgs() { return args; } public String getErrorCode() { return errorCode; } }
(2)定义异常处理类
继承org.apache.struts.action.ExceptionHandler,覆盖execute方法。
public class AppExceptionHandler extends ExceptionHandler { public ActionForward execute(Exception ex, ExceptionConfig ae, ActionMapping mapping, ActionForm formInstance, HttpServletRequest request, HttpServletResponse response) throws ServletException { if(!(ex instanceof AppException)) { return super.execute(ex, ae, mapping, formInstance, request, response); } ActionForward forward = null; ActionMessage error = null; String property = null; //获取异常处理路径,从exception mapping或者从form input if (ae.getPath() != null) { forward = new ActionForward(ae.getPath()); } else { forward = mapping.getInputForward(); } //处理异常 AppException ece =(AppException) ex; String errorCode =ece.getErrorCode(); error = new ActionMessage(errorCode, ece.getArgs()); property = error.getKey(); logException(ex); //记录异常 request.setAttribute(Globals.EXCEPTION_KEY, ex); storeException(request, property, error, forward, ae.getScope()); return forward; } }
(3)定义资源文件
在“MessageResources.properties”中进行定义,pro.basedata.item.error.add等代码是在Dao中异常抛出时定义的,见“在Dao中抛出异常”。add等代码是采用UNICODE编码。如“修改商品失败,商品代码”的UNICODE编码为“/u4fee/u6539/u5546/u54c1/u5931/u8d25,/u5546/u54c1/u4ee3/u7801”。其中,“{0}”为占位符。native2ascii.exe,此工具可以得到中文汉字对应得UNICODE字符编码。
# -- standard errors -- errors.header=<UL> errors.prefix=<LI> errors.suffix=</LI> errors.footer=</UL> pro.basedata.item.error.add=/u65b0/u589e/u5546/u54c1/u5931/u8d25 pro.basedata.item.error.delete=/u5220/u9664/u5546/u54c1/u5931/u8d25 pro.basedata.item.error.findAllItem= /u67e5/u8be2/u6240/u6709/u5546/u54c1/u5931/u8d25 pro.database.item.error.modify= /u4fee/u6539/u5546/u54c1/u5931/u8d25,/u5546/u54c1/u4ee3/u7801={0}
(4)配置struts-config.xml
1)配置公共异常处理文件
<global-exceptions> <exception key="error.exception" type="com.smartfox.pro.business.util.AppException" handler="com.smartfox.pro.web.util.AppExceptionHandler" path="/error.jsp"/> </global-exceptions>
其中,type为异常类路径,handler为异常处理类位置,path为公共异常处理页面。
2)加入资源文件
(5)在Dao中抛出异常
以修改商品信息为例。
public void modifyItem(Connection conn, Item item) { String sql="update t_items sett item_name=?, spec=?, pattern=?, category=?, unit=? " +" where item_no = ?"; PreparedStatement pstmt = null; try{ pstmt=conn.prepareStatement(sql); pstmt.setString(1, item.getItemName()); pstmt.setString(2, item.getSpec()); pstmt.setString(3, item.getPattern()); pstmt.setString(4, item.getCategory().getId()); pstmt.setString(5, item.getUnit().getId()); pstmt.setString(6, item.getItemNo()); pstmt.executeUpdate(); }catch(SQLException e){ e.printStackTrace(); throw new AppException("pro.database.item.error.modify", item.getItemNo()); }finally{ DB.closeStmt(pstmt); } }
说明:throw new AppException("pro.database.item.error.modify", item.getItemNo()); "pro.database.item.error.modify":资源文件中代码(key); item.getItemNo():为资源文件信息。参见“MessageResources.properties”文件中定义。
(6)公共异常处理页面
1)引入标记
2)使用struts标签
3)error.jsp举例
<%@ page language="java" contentType="text/html; charset=GB18030"%> <%@ taglib prefix="html" uri="http://struts.apache.org/tags-html"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>错误信息</title> </head> <body> 错误信息:<br> <hr> <html:errors/> </body> </html>