Struts2之異常處理
阿新 • • 發佈:2019-02-12
異常處理很重要,異常處理不是定義在驗證階段的,就拿登入這個功能來說吧,假如使用者填入的資訊都符合規範,通過了驗證階段,但去資料庫中查詢該使用者資訊時,發現數據庫中沒有與其匹配的資訊,則會丟擲異常,轉向錯誤頁面。
1.先來自定義一個異常,該異常繼承Exception父類
package com.exception ; //自定義異常 public class MyException extends Exception { private String message; public MyException(String message) { super(message); this.message = message ; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
2.LoginAction類的部分程式碼,假設使用者輸入的賬號和密碼不是hello,world 則丟擲異常
public String execute() throws Exception
{
if(!"hello".equals(usename) || !"world".equals(password))
{
throw new MyException("使用者名稱或密碼錯誤,您發現了吧!");
}
return "success" ;
}
3.異常又分為 區域性異常處理 和 全域性異常處理
在struts.xml中宣告捕捉異常,使其轉成自定義錯誤提示介面
區域性異常處理,定義在action標籤內:
struts.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <package name="struts2" extends="struts-default"> <!-- name="login" 這個名字可以自己定義 要和 提交表單的那個action名字一致 --> <action name="login" class="com.struts2.LoginAction"> <!-- 區域性 異常處理 --> <exception-mapping result="myexception1" exception="com.exception.MyException"> </exception-mapping> <!-- 異常跳轉的介面 --> <result name="myexception1">/error.jsp</result> <!-- name="success" 這個名字要和LoginAction.java 的 execute() 方法的返回值一致 --> <result name="success">/result.jsp</result> </action> </package> </struts>
全域性異常處理,定義在action標籤外:
struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="struts2" extends="struts-default">
<!-- 全域性 異常處理 -->
<global-results>
<result name="myexception1">/error.jsp</result>
</global-results>
<global-exception-mappings>
<exception-mapping result="myexception1"
exception="com.exception.MyException">
</exception-mapping>
</global-exception-mappings>
<!-- name="login" 這個名字可以自己定義 要和 提交表單的那個action名字一致 -->
<action name="login" class="com.struts2.LoginAction">
<!-- name="success"
這個名字要和LoginAction.java 的 execute() 方法的返回值一致
-->
<result name="success">/result.jsp</result>
</action>
</package>
</struts>
4.錯誤頁面error.jsp,
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<body>
<!-- 這個exception 是 exception="com.exception.MyException" -->
<s:property value="exception.message"/>
</body>
</html>
小結:
區域性異常處理比全域性異常處理高,並且可覆蓋全域性異常處理,如果定義了全域性異常對映,那麼會對所有的Action生效,反之定義了局部異常對映則會對當前Action生效,
如果在全域性區域和區域性區域定義了相同的異常對映,首先去區域性異常區域找result結果頁面,如果找到了,則直接跳轉到錯誤結果頁面,不管全域性有沒有相同的結果,都被區域性所覆蓋,如果在區域性區域沒找到,則去全域性區域找。