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>