- Java代碼
- //action層執行數據添加操作
- public String save(){
- try{
- //調用service的save方法
- service.save(obj);
- }catch(Exception e){
- throw new RuntimeException("添加數據時發生錯誤!",e);
- }
- return "success";
- }
- <interceptors>
- <!-- 聲明攔截器 -->
- <interceptor name="errorInterceptor" class="cn.itcast.elec.util.ErrorInterceptor" />
- <!-- 配置攔截器棧 -->
- <interceptor-stack name="myErrorInterceptor">
- <interceptor-ref name="defaultStack" />
- <interceptor-ref name="errorInterceptor" />
- </interceptor-stack>
- </interceptors>
- <!-- 覆蓋底層的攔截器棧 對包中的所有action都有效 -->
- <default-interceptor-ref name="myErrorInterceptor"/>
-
- <global-results>
- <result name="errorMsg">/errorMsg.jsp</result>
- </global-results>
- <global-exception-mappings>
- <exception-mapping result="errorMsg" exception="java.lang.Exception"></exception-mapping>
- </global-exception-mappings>
攔截器的Java代碼
- public class ErrorInterceptor implements Interceptor {
- public void init() {
- }
- public String intercept(ActionInvocation actioninvocation) {
- String result = null; // Action的返回值
- try {
- // 運行被攔截的Action,期間如果發生異常會被catch住
- result = actioninvocation.invoke();
- return result;
- } catch (Exception e) {
- /**
- * 處理異常
- */
- String errorMsg = "出現錯誤信息,請查看日誌!";
- //通過instanceof判斷到底是什麼異常類型
- if (e instanceof RuntimeException) {
- //未知的運行時異常
- RuntimeException re = (RuntimeException) e;
- //re.printStackTrace();
- errorMsg = re.getMessage().trim();
- }
- //把自定義錯誤信息
- HttpServletRequest request = (HttpServletRequest) actioninvocation
- .getInvocationContext().get(StrutsStatics.HTTP_REQUEST);
- /**
- * 發送錯誤消息到頁面
- */
- request.setAttribute("errorMsg", errorMsg);
- /**
- * log4j記錄日誌
- */
- Log log = LogFactory
- .getLog(actioninvocation.getAction().getClass());
- log.error(errorMsg, e);
- return "errorMsg";
- }// ...end of catch
- }
- public void destroy() {
- }
- }
- <body>
- <s:if test="%{#request.errorMsg==null}">
- <p>對不起,系統發生了未知的錯誤,請查看日誌</p>
- </s:if>
- <s:else>
- <p>${requestScope.errorMsg}</p>
- </s:else>
- </body>
Struts2配置文件代碼
- <global-results>
- <result name="errorMsg">/errorMsg.jsp</result>
- </global-results>
- <global-exception-mappings>
- <exception-mapping result="errorMsg" exception="java.lang.Exception"></exception-mapping>
- </global-exception-mappings>