歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Struts處理自定義異常

Struts處理自定義異常

日期:2017/3/1 10:27:10   编辑:Linux編程

很多時候我們會用到自定義異常來表示特定的錯誤情況,自定義異常比較簡單,只要分清是運行時異常還是非運行時異常即可,運行時異常不需要捕獲,繼承自RuntimeException,是由容器自己拋出,例如空指針異常。

非運行時異常繼承自Exception,在拋出後需要捕獲,例如文件未找到異常。

此處我們用的是非運行時異常,首先定義一個異常LoginException:

  1. /**
  2. * 類描述:登錄相關異常
  3. *
  4. * @author ming.li <a href="http://www.linuxidc.com">www.linuxidc.com</a>
  5. * @time 2011-4-27 下午01:08:11
  6. */
  7. public class LoginException extends Exception {
  8. /** 版本號 */
  9. private static final long serialVersionUID = 5843727837651089745L;
  10. /** 錯誤碼 */
  11. private String messageKey;
  12. /** 參數 */
  13. private Object[] params;
  14. /**
  15. * 默認構造函數
  16. */
  17. public LoginException() {
  18. super();
  19. }
  20. /**
  21. * 登錄相關異常,頁面直接顯示錯誤信息<br/>
  22. *
  23. * @param messageKey
  24. * 錯誤碼
  25. * @param params
  26. * 參數
  27. */
  28. public LoginException(String messageKey, Object... params) {
  29. this.messageKey = messageKey;
  30. this.params = params;
  31. }
  32. /**
  33. * @return the messageKey
  34. */
  35. public String getMessageKey() {
  36. return messageKey;
  37. }
  38. /**
  39. * @return the params
  40. */
  41. public Object[] getParams() {
  42. return params;
  43. }
  44. }

這是個登錄異常,用來表示登錄情況下發生的各種錯誤。這個異常只有基本內容,可以根據你的情況自行添加。

在發生登錄錯誤時調用代碼:

  1. public String login() throws LoginException {
  2. throw new LoginException("9999");// 用戶名或密碼錯誤
  3. }

其中的9999是錯誤碼,這個可以自己定義,用來在國際化時顯示不同信息。

此時拋出了一個登錄異常的信息,我們就需要在跳轉是捕獲並顯示在頁面中。

首先在struts的action配置中捕獲此異常:

  1. <package name="login-default" namespace="/" extends="struts-default">
  2. <!-- 登錄 -->
  3. <action name="login" class="loginAction" method="login">
  4. <exception-mapping result="login" exception="com.xxx.exception.LoginException"/>
  5. <result name="success">index.jsp</result>
  6. <result name="login">login.jsp</result>
  7. </action>
  8. </package>

此時我們可以看到,當拋出LoginException時struts會捕獲並跳轉到login這個result上,進而跳轉到login.jsp。

在login.jsp中我們就需要去顯示異常信息:

  1. <%@taglib prefix="s" uri="/struts-tags"%>
  2. <%@taglib prefix="c" uri="http://java.sun.com/jstl/core"%>
  3. <!-- 異常信息顯示 -->
  4. <c:if test="${!empty exception}"><s:property value="%{getText(exception.messageKey)}"/></c:if>

這樣異常信息就會被顯示了。

Copyright © Linux教程網 All Rights Reserved