在Struts2中配置了全局异常后,出现异常后可以直接往外抛,则异常会直接交给Struts2去处理,Struts2配置全局异常需要配置<global-exception-mappings>或者<exception-mapping>来进行异常个管理。(<exception-mapping>是配置在Action中)
用于异常处理的<exception-mapping>标签可以配置在Action中,也可以配置在<global-exception-mappings>,顾名思义<global-exception-mappings>就是全局异常,当然执行Action的时候发生异常时,如果在Action中没有捕获异常而是抛出异常的话,struts2会首先在正在执行的Action中查找<exception-mapping>,寻找对应的Exception进行处理,如果找不到,才会去<global-exception-mappings>去寻找对应的Exception处理,如果还是找不到的话,就只好抛出异常了。
使用步骤
一、编写Action
import java.util.Map;
import org.apache.struts2.interceptor.RequestAware;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.util.ValueStack;
public class Product implements RequestAware,SessionAware{
public String save(){
int i = 10/0;//抛出一个异常
return "success";
}
}
二、struts.xml 配置
<!-- OGNL -->
<package name="OGNLTestAction" extends="struts-default">
<!--全局结果集 -->
<global-results>
<result>/OGNLTest/product_view.jsp</result>
</global-results>
<!-- 配置全局异常 -->
<global-exception-mappings>
<exception-mapping result="input" exception="java.lang.ArithmeticException"></exception-mapping>
</global-exception-mappings>
<action name="product_save1" class="zhuojing.JGNLTest.Product" method="save">
<result name="input">/OGNLTest/product_sub.jsp</result>
</action>
</package>
注:访问action时,若出现异常,则Struts2会找global-exception-mappings中对应的异常,然后根据exception-mapping result="input" 中result的值去action中需要result,也就是这上面例子中出现异常会跳转到/OGNLTest/product_sub.jsp,若没有出现异常,会去global-results标签中找result,默认name是success,(global-results是全局结果,也可以在action中配置一个name的success的result,进行野蛮的跳转),也就是所没有异常时跳转/OGNLTest/product_view.jsp
这边 global-results和global-exception-mappings作用比较类似,所以案例用来global-results,也可以在Action中配置exception-mapping,这边就具体说明了