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对象
三、实现步骤
创建自己的异常处理类
Java代码
package com.fengzhiyin.common;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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.config.ExceptionConfig;
import org.apache.struts.util.ModuleException;
public class ExceptionHandler extends org.apache.struts.action.ExceptionHandler {
/**
* Logger for this class
*/
private static final Log logger = LogFactory.getLog(ExceptionHandler.class);
/*
* (non-Javadoc)
*/
@Override
public ActionForward execute(Exception ex, ExceptionConfig config, ActionMapping mapping, ActionForm formInstance, HttpServletRequest request,
HttpServletResponse response) throws ServletException {
if (logger.isDebugEnabled()) {
logger.debug("execute(Exception, ExceptionConfig, ActionMapping, ActionForm, HttpServletRequest, HttpServletResponse) - start");
}
logger.warn("action exception.", ex);
String f = (String) request.getAttribute("exceptionForward");
request.setAttribute("javax.servlet.jsp.jspException", ex);
ActionForward forward = null;
ActionMessage error = null;
String property = null;
// Build the forward from the exception mapping if it exists
// or from the form input
if (config.getPath() != null) {
forward = new ActionForward(config.getPath());
} else if (f != null) {
forward = f.indexOf(".jsp") == -1 ? mapping.findForward(f) : new ActionForward(f);
} else {
forward = mapping.getInputForward();
}
// Figure out the error
if (ex instanceof ModuleException) {
error = ((ModuleException) ex).getActionMessage();
property = ((ModuleException) ex).getProperty();
} else {
error = new ActionMessage(config.getKey(), ex.getMessage());
property = error.getKey();
}
this.logException(ex);
// Store the exception
request.setAttribute(Globals.EXCEPTION_KEY, ex);
this.storeException(request, property, error, forward, config.getScope());
if (logger.isDebugEnabled()) {
logger.debug("execute(Exception, ExceptionConfig, ActionMapping, ActionForm, HttpServletRequest, HttpServletResponse) - end");
}
return forward;
}
}
定义异常处理配置文件 全局异常 在struts-config.xml中定义<global-exceptions />
Xml代码
<global-exceptions><!-- 元素可以包含一个或者多个<exception> -->
<exception
key="error.common"<!-- <message-resources parameter="MessageResources" />中的key -->
type="com.fengzhiyin.exception.ExistException"<!-- 指定需要处理异常类的名字 -->
handler="com.bjnv.water.common.ExceptionHandler" <!-- 指定异常处理类默认是ExceptionHandler -->
path="/jsp/common/error.jsp"<!-- 指定当前异常发生的时候转发的路径 -->
scope="request"><!-- 指定ActionMessages实例存放的范围 -->
</exception>
</global-exceptions>
上述代码在struts-config.xml中定义了一个全局异常,它的作用是抛出ExistException(本处的意思是当在添加用户时候发现该用户名已经存在)异常的时候返回到error.jsp中,并且携带自定的比较规范的异常信息expired.existName,expired.existName可以在应用程序的资源配置文件中找到,如: expired.existName=你要添加的用户名称已经存在,请添加新的名称! 局部异常 在struts-config.xml中定义<global-exceptions />
Xml代码
<action-mappings>
<action path=”/waterUser”
type=”**Action”
name=”*Form”>
<exception key=”<SPAN style="FONT-SIZE: x-small">expired.existName</SPAN>”
type=” com.fengzhiyin.exception.ExistException”
path=”/error.jsp”/>
<forward name=”success” path=”***”/>
</action>
</action-mappings>
创建异常信息显示页面
Java代码
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<html:html locale="true">
<head>
<title> Exception Handler</title>
<html:base />
</head>
<body>
<h1>系统出现一个意外</h1>
请将下面的提示信息反馈给你的系统管理员:<br>
<html:errors /> <!--将在这里显示”<SPAN style="FONT-SIZE: x-small; COLOR: #0000ff">你要添加的用户名称已经存在,请添加新的名称!</SPAN>”-->
</body>
</html:html>
创建测试action
Java代码
public class **Action extends BaseAction {
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)throws Exception {
throw com.fengzhiyin.exception.ExistException();
}
}
|
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理