Struts 1.x 异常处理方式(jsp生成形式,非ajax)
基本原理:
如果有异常,把异常存入request里,然后转发到指定的jsp页面,然后可以用struts的error标签取出来
ActionErrors errors = new ActionErrors();
errors.add( ActionErrors.GLOBAL_ERROR,new ActionError("error.application.exception"));
saveErrors(request, errors);
return (new ActionForward(mapping.getInput()));
方式1 用一个BaseAction 继承DispatchAction改写perform方法
详细参见http://www.cnblogs.com/kapok/archive/2005/10/15/255395.html
public class BaseDispatchAction extends DispatchAction {
public ActionForward perform(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response)throws IOException, ServletException {
// 获取方法名的key参数
String parameter = mapping.getParameter();
String name = request.getParameter(parameter);
Method method = null;
method = getMethod(name);
ActionForward forward = null;
try {
Object args[] = { mapping, form, request, response };
forward = (ActionForward) method.invoke(this, args);
}catch (InvocationTargetException e) {
if (e.getTargetException() instanceof BaseException) {
forward = processExceptions(request, mapping, e);
}if (e.getTargetException() instanceof ApplicationException) {
forward = processExceptions(request, mapping, e);
} else if (e.getTargetException() instanceof SystemException) {
request.setAttribute("EXCEPTION_KEY", e);
//直接跳到错误页面去
forward = mapping.findForward("systemerror");
}
}
return (forward);
}
protected ActionForward processExceptions( HttpServletRequest request, ActionMapping mapping,Throwable throwable) {
ActionErrors errors = new ActionErrors();
ActionForward forward = null;
if (mapping.getInput() != null) {
forward = new ActionForward(mapping.getInput());
} else if (mapping.findForward("FAILURE_KEY") != null) {
forward = mapping.findForward("FAILURE_KEY");
}
saveErrors(request, errors);
return forward;
}
}
方式2 使用 ExceptionHandler
配置
<global-exceptions>
<exception key="todo" type="org.chage.exception.BaseException" handler="org.chage.exception.MyExceptionHandler" />
</global-exceptions>
public class MyExceptionHandler extends ExceptionHandler {
public ActionForward execute( Exception exception,ExceptionConfig config, ActionMapping mapping,ActionForm form, HttpServletRequest request,
HttpServletResponse response)throws ServletException {
request.setAttribute("exception", exception);
return mapping.getInputForward();
}}
在页面上:
<logic:present name="exception">
<bean:write name="exception"/>
</logic:present>

浙公网安备 33010602011771号