记录一下全局异常处理的过程;处理主动抛出的异常,转向错误提示页面。
1、写一个自己的异常,继承runtimeexception,从父类生成构造方法;
package me.yndy.srtp.exception;
@SuppressWarnings("serial")
public class ErrorException extends RuntimeException {
public ErrorException() {
super();
}
public ErrorException(String message, Throwable cause) {
super(message, cause);
}
public ErrorException(String message) {
super(message);
}
public ErrorException(Throwable cause) {
super(cause);
}
}
2.代码中需要手动抛出异常
if(content==null||"".equals(content.trim())) {
throw new ErrorException("内容不能为空!");//手动抛出异常
}
3.在struts.xml文件中敌营全局异常,异常跳转界面为error.jsp
<struts>
<!-- 设置扩展名 -->
<constant name="struts.action.extension" value="action,do" />
<!-- 设置修改了配置文件不用重新启动 -->
<constant name="struts.configuration.xml.reload" value="true" />
<package name="default" namespace="/" extends="struts-default">
<!--配置全集结果集 , -->
<global-results>
<result name="error">/error.jsp</result>
</global-results>
<!-- 异常处理 -->
<global-exception-mappings>
<exception-mapping result="error"
exception="me.yndy.srtp.exception.ErrorException">
</exception-mapping>
</global-exception-mappings>
<!-- 通配符匹配action -->
<action name="*_*" class="me.yndy.srtp.controller.{1}Action"
method="{2}">
<result name="success">/{1}/{2}.jsp</result>
<result name="input">/{1}/{2}Input.jsp</result>
<result name="redirect" type="redirect">/${#urlAction}</result>
</action>
</package>
</struts>
4、error.jsp
<div class="content">
<!-- 以后加上bootstrap的大屏幕,增加界面的统一性-->
<p>${exception.message}</p>
<!--返回上一页,此种用法不会丢失上一页的内容 -->
<p><a href="javascript:history.go(-1);">点此返回</a></p>
</div>
总结:这样就配置了全局异常处理,可以对所有的action生效,可以配置局部异常处理,在struts.xml中的action内,配置,可以针对单个action生效。如果在某个action中配置了局部异常处理,一个异常同时对应了局部异常和全局异常,那么会执行局部异常处理的代码,局部异常处理的优先级高,会将全局的覆盖了。