---
title: "Struts1x项目开发中的统一异常处理"
author: "java_cd"
date: "2010-03-03T14:17:21Z"
tags: []
categories: ["Web前端"]
slug: "struts1x"
draft: false
lastmod: "2010-03-03T14:17:21Z"
id: 606859
url: "https://java-cd.iteye.com/blog/606859"
---

在项目开发中如果能使用统一异常处理的话，则不但可以简化开发过程，而且还更容易团队的开发与合作，事半功倍。以下通过使用struts1X 结合实现一个项目的统一异常处理解决方案的例子： 

第一步： 
  配置好Struts整合web。 

第二步： 
  编写统一异常类：SystemException.java 
Java代码 
package com.changtu.oa.managers;   
/**  
 * 统一异常类  
 * 用于存储异常信息，供抛出  
 * @author Mike  
 */  
public class SystemException extends RuntimeException {   
    //异常代码   
    private String key;   
    private Object values;   
    // 构造器重载   
    public SystemException() {   
        super();   
    }   
    public SystemException(String message, Throwable throwable) {   
        super(message, throwable);   
    }   
    public SystemException(String message) {   
        super(message);   
    }   
    public SystemException(Throwable throwable) {   
        super(throwable);   
    }   
    public SystemException(String message,String key){   
        super(message);   
        this.key = key;   
    }   
    public SystemException(String message,String key,Object value){   
        super(message);   
        this.key = key;   
        this.values = new Object{value};   
    }   
    public SystemException(String message,String key,Object values){   
        super(message);   
        this.key = key;   
        this.values = values;   
    }   
    public String getKey() {   
        return key;   
    }   
    public Object getValues() {   
        return values;   
    }   
}  

package com.changtu.oa.managers;
/**
 * 统一异常类
 * 用于存储异常信息，供抛出
 * @author Mike
 */
public class SystemException extends RuntimeException {
	//异常代码
	private String key;
	private Object values;
	// 构造器重载
	public SystemException() {
		super();
	}
	public SystemException(String message, Throwable throwable) {
		super(message, throwable);
	}
	public SystemException(String message) {
		super(message);
	}
	public SystemException(Throwable throwable) {
		super(throwable);
	}
	public SystemException(String message,String key){
		super(message);
		this.key = key;
	}
	public SystemException(String message,String key,Object value){
		super(message);
		this.key = key;
		this.values = new Object{value};
	}
	public SystemException(String message,String key,Object values){
		super(message);
		this.key = key;
		this.values = values;
	}
	public String getKey() {
		return key;
	}
	public Object getValues() {
		return values;
	}
}



  编写统一异常处理类：SystemExceptionHandler.java 
Java代码 
package com.changtu.oa.web;   
…   
import com.changtu.oa.managers.SystemException;   
  
/**  
 * 统一异常处理类  
 * @author Mike  
 */  
public class SystemExceptionHandler extends ExceptionHandler {   
    private static Log logger = LogFactory.getLog(SystemExceptionHandler.class);   
    /**  
     * 处理SystemException异常  
     */  
    @Override  
    public ActionForward execute(   
            Exception ex,    
            ExceptionConfig ae,    
            ActionMapping mapping,    
            ActionForm formInstance,    
            HttpServletRequest request,    
            HttpServletResponse response) throws ServletException {   
           
        ActionForward forward = null;   
        if(ae.getPath() != null){   
            forward = new ActionForward(ae.getPath());   
        }else{   
            forward = mapping.getInputForward();   
        }   
           
        logger.debug("出现异常", ex);   
           
        // 在控制台显示的异常信息   
        ex.printStackTrace();   
           
        // 如果抛出的异常是自定义的统一异常   
        if(ex instanceof SystemException){   
            SystemException se = (SystemException)ex;   
               
            //取出key值   
            String key = se.getKey();   
               
            // 储存异常信息......   
            ActionMessage error = null;   
            if( key == null){   
                error = new ActionMessage(ae.getKey(),se.getMessage());   
            }else{   
                if(se.getValues() != null){   
                    error = new ActionMessage(key,se.getValues());   
                }else{   
                    error = new ActionMessage(key);   
                }   
            }   
               
            this.storeException(request, key, error, forward, ae.getScope());   
               
            return forward;   
        }   
           
        return super.execute(ex, ae, mapping, formInstance, request, response);   
    }   
  
}  

package com.changtu.oa.web;
…
import com.changtu.oa.managers.SystemException;

/**
 * 统一异常处理类
 * @author Mike
 */
public class SystemExceptionHandler extends ExceptionHandler {
	private static Log logger = LogFactory.getLog(SystemExceptionHandler.class);
	/**
	 * 处理SystemException异常
	 */
	@Override
	public ActionForward execute(
			Exception ex, 
			ExceptionConfig ae, 
			ActionMapping mapping, 
			ActionForm formInstance, 
			HttpServletRequest request, 
			HttpServletResponse response) throws ServletException {
		
		ActionForward forward = null;
		if(ae.getPath() != null){
			forward = new ActionForward(ae.getPath());
		}else{
			forward = mapping.getInputForward();
		}
		
		logger.debug("出现异常", ex);
		
		// 在控制台显示的异常信息
		ex.printStackTrace();
		
		// 如果抛出的异常是自定义的统一异常
		if(ex instanceof SystemException){
			SystemException se = (SystemException)ex;
			
			//取出key值
			String key = se.getKey();
			
			// 储存异常信息......
			ActionMessage error = null;
			if( key == null){
				error = new ActionMessage(ae.getKey(),se.getMessage());
			}else{
				if(se.getValues() != null){
					error = new ActionMessage(key,se.getValues());
				}else{
					error = new ActionMessage(key);
				}
			}
			
			this.storeException(request, key, error, forward, ae.getScope());
			
			return forward;
		}
		
		return super.execute(ex, ae, mapping, formInstance, request, response);
	}

}



第三步： 
  编写struts配置文件： 
    1、在src目录下新建文件名为：MessageResources.properties 资源文件，内容如下： 
       errors.detail={0} 
    2、struts-config.xml配置文件信息如下： 
    Java代码 
    <?xml version="1.0" encoding="UTF-8"?>   
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">   
  
<struts-config>   
       
    <!-- 统一异常处理 -->   
    <global-exceptions >   
        <exception    
            key="errors.detail"    
            type="java.lang.Exception"  
            path="/common/exception.jsp"  
            scope="request"  
            handler="com.changtu.oa.web.SystemExceptionHandler"  
        ></exception>   
    </global-exceptions>   
       
    <action-mappings>   
           
           
    </action-mappings>   
    <!-- 加载国际化资源文件 -->   
    <message-resources parameter="MessageResources" />       
</struts-config>   
      

    <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">

<struts-config>
	
	<!-- 统一异常处理 -->
	<global-exceptions >
		<exception 
			key="errors.detail" 
			type="java.lang.Exception"
			path="/common/exception.jsp"
			scope="request"
			handler="com.changtu.oa.web.SystemExceptionHandler"
		></exception>
	</global-exceptions>
	
	<action-mappings>
		
		
	</action-mappings>
	<!-- 加载国际化资源文件 -->
	<message-resources parameter="MessageResources" /> 	
</struts-config>
    

第四步：编写业务逻辑：UserManager.java  UserManagerImple.java 
  UserManagerImpl.java 
  Java代码 
   package com.changtu.oa.managers.impl;   
   //...   
  
public class UserManagerImpl implements UserManager {   
         
      // 登陆   
      public User login(String username, String password) {   
  
        /**  
         * 因为设置了User的auto-import="false"，所以，在这里使用  
         * HQL查询的时候，必须使用全路径的类名  
         */  
        User user = (User)getSession().createQuery(   
                "select u from com.changtu.oa.model.User u where u.username = ?")   
            .setParameter(0, username)   
            .uniqueResult();   
           
        if(user == null){   
            throw new SystemException("没有这个用户");   
        }   
           
        if(!user.getPassword().equals(password)){   
            throw new SystemException("密码错误！");   
        }   
           
        return user;   
    }   
}   
    

   package com.changtu.oa.managers.impl;
   //...

public class UserManagerImpl implements UserManager {
      
      // 登陆
      public User login(String username, String password) {

		/**
		 * 因为设置了User的auto-import="false"，所以，在这里使用
		 * HQL查询的时候，必须使用全路径的类名
		 */
		User user = (User)getSession().createQuery(
				"select u from com.changtu.oa.model.User u where u.username = ?")
			.setParameter(0, username)
			.uniqueResult();
		
		if(user == null){
			throw new SystemException("没有这个用户");
		}
		
		if(!user.getPassword().equals(password)){
			throw new SystemException("密码错误！");
		}
		
		return user;
	}
}
  


第五步：异常页面 exception.jsp 
Java代码 
<%@ page language="java" contentType="text/html; charset=GB18030"  
    pageEncoding="GB18030"%>   
<%@include file="/common/common.jsp" %>   
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">   
<html>   
<head>   
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">   
<title>Insert title here</title>   
</head>   
<body>   
<html:errors/>   
</body>   
</html>  

<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<%@include file="/common/common.jsp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>Insert title here</title>
</head>
<body>
<html:errors/>
</body>
</html>


第六步：编写自己的Action进行测试。在Action中出自定义的异常时，struts会自动根据你的配置跳转到异常界面，显示异常信息。(其中有不完整的，需自己补充)