struts自定义异常

SSH项目中利用struts的ExceptionHandler处理异常
2009-08-04 14:49

一、概述

       在Struts1.X的版本中加入了对异常的处理 Exception Handling,有了它就不需要我们用try/catch等捕获异常,一旦出现了我们已经定义的异常那么就会转到相应得页面,并且携带定制的信息。Struts框架提供了默认的异常处理org.apache.struts.action.ExceptionHandler,它的execute()方法负责处理异常。在需要实现自定义处理时重写方法,可以在配置文件定义由谁来处理Action类中掷出的某种异常。

 

二、Struts框架处理异常的流程

      struts的控制器负责捕获各种异常,包括控制器运行中本身抛出的异常,以及调用模型的业务方法时抛出的异常。当struts的控制器捕获到异常后,在异常处理代码块中,创建描述信息的actionMessage对象把它保存在acionMessages(或其子类actionErrors)对象中,然后把actionMessage保存在特定范围(配置文件中的scope)。然后可以用<html:errors />检索特定范围内的actionMessages对象

 

三、实现步骤

  1. 创建自己的异常处理类
    Java代码  复制代码
    1. package com.fengzhiyin.common;   
    2.   
    3. import javax.servlet.ServletException;   
    4. import javax.servlet.http.HttpServletRequest;   
    5. import javax.servlet.http.HttpServletResponse;   
    6.   
    7. import org.apache.commons.logging.Log;   
    8. import org.apache.commons.logging.LogFactory;   
    9. import org.apache.struts.Globals;   
    10. import org.apache.struts.action.ActionForm;   
    11. import org.apache.struts.action.ActionForward;   
    12. import org.apache.struts.action.ActionMapping;   
    13. import org.apache.struts.action.ActionMessage;   
    14. import org.apache.struts.config.ExceptionConfig;   
    15. import org.apache.struts.util.ModuleException;   
    16.   
    17. public class ExceptionHandler extends org.apache.struts.action.ExceptionHandler {   
    18.     /**
    19.       * Logger for this class
    20.       */  
    21.     private static final Log logger = LogFactory.getLog(ExceptionHandler.class);   
    22.   
    23.     /*
    24.       * (non-Javadoc)
    25.       */  
    26.     @Override  
    27.     public ActionForward execute(Exception ex, ExceptionConfig config, ActionMapping mapping, ActionForm formInstance, HttpServletRequest request,   
    28.              HttpServletResponse response) throws ServletException {   
    29.         if (logger.isDebugEnabled()) {   
    30.              logger.debug("execute(Exception, ExceptionConfig, ActionMapping, ActionForm, HttpServletRequest, HttpServletResponse) - start");   
    31.          }   
    32.   
    33.          logger.warn("action exception.", ex);   
    34.   
    35.          String f = (String) request.getAttribute("exceptionForward");   
    36.          request.setAttribute("javax.servlet.jsp.jspException", ex);   
    37.   
    38.          ActionForward forward = null;   
    39.          ActionMessage error = null;   
    40.          String property = null;   
    41.   
    42.         // Build the forward from the exception mapping if it exists   
    43.         // or from the form input   
    44.         if (config.getPath() != null) {   
    45.              forward = new ActionForward(config.getPath());   
    46.          } else if (f != null) {   
    47.              forward = f.indexOf(".jsp") == -1 ? mapping.findForward(f) : new ActionForward(f);   
    48.          } else {   
    49.              forward = mapping.getInputForward();   
    50.          }   
    51.   
    52.         // Figure out the error   
    53.         if (ex instanceof ModuleException) {   
    54.              error = ((ModuleException) ex).getActionMessage();   
    55.              property = ((ModuleException) ex).getProperty();   
    56.          } else {   
    57.              error = new ActionMessage(config.getKey(), ex.getMessage());   
    58.              property = error.getKey();   
    59.          }   
    60.   
    61.         this.logException(ex);   
    62.   
    63.         // Store the exception   
    64.          request.setAttribute(Globals.EXCEPTION_KEY, ex);   
    65.         this.storeException(request, property, error, forward, config.getScope());   
    66.   
    67.         if (logger.isDebugEnabled()) {   
    68.              logger.debug("execute(Exception, ExceptionConfig, ActionMapping, ActionForm, HttpServletRequest, HttpServletResponse) - end");   
    69.          }   
    70.         return forward;   
    71.      }   
    72.   
    73. }  
  2. 定义异常处理配置文件
    全局异常 在struts-config.xml中定义<global-exceptions />
    Xml代码  复制代码
    1. <global-exceptions><!-- 元素可以包含一个或者多个<exception> -->  
    2.     <exception   
    3.         key="error.common"<!-- <message-resources parameter="MessageResources" />中的key -->  
    4.         type="com.fengzhiyin.exception.ExistException"<!-- 指定需要处理异常类的名字 -->  
    5.         handler="com.bjnv.water.common.ExceptionHandler" <!-- 指定异常处理类默认是ExceptionHandler -->  
    6.         path="/jsp/common/error.jsp"<!-- 指定当前异常发生的时候转发的路径 -->  
    7.         scope="request"><!-- 指定ActionMessages实例存放的范围 -->  
    8.     </exception>  
    9. </global-exceptions>  
    上述代码在struts-config.xml中定义了一个全局异常,它的作用是抛出ExistException(本处的意思是当在添加用户时候发现该用户名已经存在)异常的时候返回到error.jsp中,并且携带自定的比较规范的异常信息expired.existName,expired.existName可以在应用程序的资源配置文件中找到,如:
      expired.existName=你要添加的用户名称已经存在,请添加新的名称!
    局部异常 在struts-config.xml中定义<global-exceptions />
    Xml代码  复制代码
    1. <action-mappings>  
    2.   <action path=”/waterUser”   
    3.         type=”**Action”   
    4.         name=”*Form”>  
    5.     <exception key=”<SPAN style="FONT-SIZE: x-small">expired.existName</SPAN>”   
    6.         type=” com.fengzhiyin.exception.ExistException”   
    7.         path=”/error.jsp”/>  
    8.         <forward name=”success” path=”***”/>  
    9.   </action>  
    10. </action-mappings>  
  3. 创建异常信息显示页面
    Java代码  复制代码
    1. <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>   
    2.   <%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>   
    3.   <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>   
    4.   <html:html locale="true">   
    5.   <head>   
    6.    <title> Exception Handler</title>   
    7.    <html:base />   
    8.    </head>   
    9.    <body>   
    10.    <h1>系统出现一个意外</h1>   
    11.    请将下面的提示信息反馈给你的系统管理员:<br>   
    12.    <html:errors /> <!--将在这里显示”<SPAN style="FONT-SIZE: x-small; COLOR: #0000ff">你要添加的用户名称已经存在,请添加新的名称!</SPAN>”-->   
    13.    </body>   
    14.   </html:html>  

  4. 创建测试action
    Java代码  复制代码
    1. public class **Action extends BaseAction {   
    2.    public ActionForward execute(ActionMapping mapping,   
    3.      ActionForm form,   
    4.      HttpServletRequest request,   
    5.      HttpServletResponse response)throws Exception {   
    6.      throw com.fengzhiyin.exception.ExistException();   
    7.    }   
    8. }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值