針對運行時產生的異常,除了try/catch捕獲之后進行自定義處理,還可以考慮使用struts2提供的全局結果集。
Action:
1 package demo.action;
2
3 public class HelloWorld {
4
5 public String execute() throws Exception {
6 //模擬一個異常
7 if (true) {
8 throw new Exception("Exception test");
9 }
10 return "success";
11 }
12
13 }
14
struts.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE struts PUBLIC
3 "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
4 "http://struts.apache.org/dtds/struts-2.3.dtd">
5 <struts>
6
7 <constant name="struts.devMode" value="true" />
8 <package name="helloworld" extends="struts-default" namespace="/">
9
10 <global-results>
11 <!-- 指定一個頁面作為異常頁面 -->
12 <result name="error">/error.jsp</result>
13 </global-results>
14
15 <global-exception-mappings>
16 <!-- 配置需要捕獲的異常類型,以及返回結果 -->
17 <exception-mapping result="error" exception="Exception" />
18 </global-exception-mappings>
19
20 <action name="hello" class="demo.action.HelloWorld">
21 <result name="success">/helloWorld.jsp</result>
22 </action>
23
24 </package>
25
26 </struts>
全局異常結果集的配置很簡便,可以配置一些404或者一些通用的異常頁面,在頁面中使用${exception.message}就可以獲得異常信息。