posts - 68, comments - 19, trackbacks - 0, articles - 1

Struts1自动异常处理

Posted on 2011-02-25 21:05 viery 阅读(546) 评论(0)  编辑  收藏
1.异常类

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,String message) {
    super(message);
    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;
  }

 

}

2.处理器

public class SystemExceptionHandler extends ExceptionHandler {

 /**
  * 处理SystenException异常
  */
 @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);

 }

}

3.struts配置
 <global-exceptions>
  <exception key="errors.detail"
       type="com.v.oa.common.SystemException"
       path="/common/exception.jsp"
       scope="request"
       handler="com.v.oa.common.SystemExceptionHandler">
      
  </exception>
 </global-exceptions>
4.<html:errors/>
5.国际化资源文件 可以用0001编码 类似oracle异常编码

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


网站导航: