疯狂

STANDING ON THE SHOULDERS OF GIANTS
posts - 481, comments - 486, trackbacks - 0, articles - 1
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

struts中利用ExceptionHandler处理异常

Posted on 2007-11-22 13:33 疯狂 阅读(3852) 评论(5)  编辑  收藏

        在Struts1.X的版本中加入了对异常的处理,Exception Handling,有了它就不需要我们用try/catch等捕获异常,一旦出现了我们已经定义的异常那么就会转到相应得页面,并且携带定制的信息。STRUTS框架提供了默认的异常处理org.apache.struts.action.ExceptionHandler,他的execute()方法负责处理异常。在需要实现自定义处理时重写方法,可以在配置文件定义由谁来处理Action类中掷出的某种异常。
       Struts框架处理异常的流程
       struts的控制器负责捕获各种异常,包括控制器运行中本身抛出的异常,以及调用模型的业务方法时抛出的异常。当struts的控制器捕获到
异常后,在异常处理代码块中,创建描述信息的actionmessage对象把它保存在acionmessages(或其子类actionerrors)对象中,然后把ACTIONMESSAGES保存在特定范围(配置文件中的scope)。然后可以用<html:errors>检索特定范围内的actionmessages对象。

下面是一个全局的处理类的例子:
       
  首先介绍<global-exception>元素: 
 <global-exceptions>//元素可以包含一个或者多个<exception>元素
  <exception 
   className=""//指定和元素对应的配置类,默认的不用动
   bundle=""//Resource Bundle
   key="..." // <message-resources parameter="MessageResources" />中的key
   type="java.lang.Exception"//指定需要处理异常类的名字,必须
   handler="com.myHander.SystemExceptionHandler"指定异常处理类默认是ExceptionHandler,
   path="/pub_exception.jsp"//指定当前异常发生的时候转发的路径
   scope="request"//指定ActionMessages实例存放的范围
        ......
  >

</exception>
 </global-exceptions>

 
 
 
2,定义自己的异常类:SystemException

package com.ex;

public class SystemException extends RuntimeException {

 private String key;//得到本地资源文件key
 private Object[] values;
 
 public SystemException() {
  super();
 }

 public SystemException(String message, Throwable arg1) {
  super(message, arg1);
 }

 public SystemException(String message) {
  super(message);
 }

 public SystemException(Throwable message) {
  super(message);
 }

 public SystemException(String key,String message, Throwable arg1) {
  super(message, arg1);
  this.key = key;
 }

 public SystemException(String key,Object value) {
  super();
  this.key = key;
  values = new Object[]{value};
 }
 
 public SystemException(String key,Object value1,Object value2) {
  super();
  this.key = key;
  values = new Object[]{value1,value2};
 }
 
 public SystemException(String key,Object[] values) {
  super();
  this.key = key;
  this.values = values;
 }

 public String getKey() {
  return key;
 }

 public Object[] getValues() {
  return values;
 }

}

定义自己的异常类处理类:SystemExceptionHandler,extendExceptionHandler,覆盖execute方法,处理自己的异常类,其他的异常有父类自己处理


package com.ex;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.Globals;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ExceptionHandler;
import org.apache.struts.config.ExceptionConfig;

import com.ex.SystemException;

public class SystemExceptionHandler extends ExceptionHandler {

 @Override
 public ActionForward execute(Exception ex, ExceptionConfig ae,
   ActionMapping mapping, ActionForm formInstance,
   HttpServletRequest request, HttpServletResponse response)
   throws ServletException {
  
        ActionForward forward = null;
        ActionMessage error = null;
        String property = null;  
  
        if (ae.getPath() != null) {//配置文件中的path
            forward = new ActionForward(ae.getPath());
        } else {
            forward = mapping.getInputForward();//
如果没有找到path,转到input配置的路径
        }  
  
        this.logException(ex);
        
  
//处理自定义的异常类SystemException
  if(ex instanceof SystemException){
   SystemException se = (SystemException)ex;
   //如果只有message,而没有key
   if(se.getKey() == null){
    error = new ActionMessage(ae.getKey(), ex.getMessage());
    property = ae.getKey();
   }else{ //SystemException中有key值

    error = new ActionMessage(se.getKey(),se.getValues());
    property = se.getKey();
   }
         request.setAttribute(Globals.EXCEPTION_KEY, ex);
         this.storeException(request, property, error, forward, ae.getScope());
        
         return forward;
  }
  
  return super.execute(ex, ae, mapping, formInstance, request, response);
 }
 
}
struts-config.xml中配置:

    <global-exceptions>
  <exception
   type="java.lang.Exception"
   handler="com.ex.SystemExceptionHandler"
   path="/pub_exception.jsp"
   scope="request"
  >
  </exception>
 </global-exceptions>

3,pub_exception.jsp页面;
  
获得异常:<html:errors/>//当然:引入<%@ taglib prefix="html"  uri="http://struts.apache.org/tags-html" %>
4,测试:TestHander(业务逻辑类)

package com.ex;

import com.ex.SystemException;

public class TestHander {

    public void test(int t){
     
     if(t>2){
      
throw new SystemException("不能大于2!");
                //
或者throw new SystemException("testkey",t);调用SystemException中的SystemException(String key,Object value) 构成方法得到资源文件定义的信息,当然 在MessageResources.properties文件里加上testkey= {0} con't greater than 2!当然还要加上  <message-resources parameter="MessageResources" />
                
     }
     
    }
}
5,Action类:调用TestHander的test方法:
      (主要代码) new TestHander().test(3);
6,jsp调用acyion页面页面:
  <a href="testhander.do">异常</a>
一点击就会转向pub_exception.jsp页面显示:不能大于2!

 


评论

# re: struts中利用ExceptionHandler处理异常[未登录]  回复  更多评论   

2007-11-22 17:54 by xiaoxiao
up,正在学

# re: struts中利用ExceptionHandler处理异常  回复  更多评论   

2008-04-09 10:29 by binggo
在配置文件中exception 不指定key好像是不可以的。
如果不可以的话public SystemException(String message) 这个构造函数也没有很么意义。

# re: struts中利用ExceptionHandler处理异常  回复  更多评论   

2008-06-14 11:39 by 浪子回头
请不要乱贴!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

# re: struts中利用ExceptionHandler处理异常  回复  更多评论   

2008-12-09 14:44 by s
s

# re: struts中利用ExceptionHandler处理异常  回复  更多评论   

2009-01-05 22:23 by anms
<global-exceptions>
<exception key="some.key"
type="com.framework.exception.BaseException"
handler="com.ramework.struts.action.ExceptionHandlerAction" />
</global-exceptions>

我看到的一个异常处理 没有Path=“uir...”那么它是怎样转到一个页面上的呀

只有注册用户登录后才能发表评论。


网站导航: