Struts声明式异常

编程式异常 :

即我们在Action中调用业务逻辑层对象的方法时,用try{}catch的方式来截获异常之后,手工对异常进行处理。在编程式异常处理的时候,我们可以使用struts的消息处理机制来对这些异常信息进行处理。

编程式异常的处理过程:1,截获异常,2创建相应的异常信息,3传递异常信息,4转向相应的页面处理异常。

 

声明式异常(自动处理的异常):

声明式异常(自动处理的异常)
* 在struts-config.xml文件中配置<exeception/>标签
* 理解局部和全局exception
* 注意局部<exception/>标签需要配置到<forward/>标签的前面,详见dtd中的约束

<exeception/>标签中的属性说明:
* key:指异常信息对应的国际化消息文本,这个key值需要在国际化资源文件中定义
* type: 处理那种异常(异常类的完整路径),
* path: 定义一但出现异常,需要转向那个页面,如果不定义path,
         默认情况下将使用<action>标签中input属性对应的页面 ,path的优先级高。
* scope:可以取值request和session,默认为request
* handler:异常的处理类,struts默认采用org.apache.struts.action.ExceptionHandler,
            如果做个性化的异常处理可以继承此类覆写相应的方法

首先在struts-config.xml中做配置:

 

<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE struts-config PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
          "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">

<struts-config>

 <form-beans>
  <form-bean name="loginForm" type="com.mine.struts.LoginActionForm"/>
 </form-beans>
 
 <global-exceptions>//用于配置全局exception,当发生当前配的异常时,都会在这里转
 <!--
   <exception key="user.not.found" type="com.mine.struts.UserNotFoundException" path="/login_error.jsp"/>
   <exception key="user.password.error" type="com.mine.struts.PasswordErrorException" path="/login_error.jsp"/>
  -->
 
  <!--
  <exception key="user.not.found" type="com.mine.struts.UserNotFoundException" handler="org.apache.struts.action.ExceptionHandler"/>
  <exception key="user.password.error" type="com.mine.struts.PasswordErrorException" handler="org.apache.struts.action.ExceptionHandler"/>
  -->
 
  <!--
  <exception key="error.exception" type="com.mine.struts.ErrorCodeException" handler="com.bjsxt.struts.ErrorCodeExceptionHandler"/>
   -->
   <!--
   <exception key="error.exception" type="com.mine.struts.AppException" handler="com.bjsxt.struts.AppExceptionHandler"/>
    --> 
  
   <exception key="error.exception" type="com.mine.struts.AppException"/>
 </global-exceptions>
  
 <action-mappings>
  <action path="/login"
    type="com.mine.struts.LoginAction"
    name="loginForm"
    scope="request"
    validate="false"
    input="/login.jsp"
  > 
  <!-- //异常的配置使用exception标签。这个标签的配置要在forward标签的前面配置,这个是由dtd决定的,当exception在这里配置时,只适合当前的exception,可以配置全局的exception
   <exception key="user.not.found" type="com.mine.struts.UserNotFoundException" path="/login_error.jsp"/>
   <exception key="user.password.error" type="com.mine.struts.PasswordErrorException" path="/login_error.jsp"/>
   --> 
   <forward name="success" path="/login_success.jsp"/>
   <forward name="error" path="/login.jsp"/>
  </action>
  
  <action path="/changelang"
    type="com.mine.struts.ChangeLanguageAction"
  >
   <forward name="index" path="/index.jsp"/>
  </action>
  
  <action path="/login1"
    type="org.apache.struts.actions.ForwardAction"
    parameter="/login.jsp"
  ></action>
 </action-mappings>
 
 <message-resources parameter="res.MessageResources" />
</struts-config>

 

在exception 标签里有个key属性,这个是国际化消息文本,用于当发生异常的时候的提示信息:

 

# -- standard errors --
errors.header=<UL>
errors.prefix=<LI><font color="red">
errors.suffix=</font></LI>
errors.footer=</UL>


user.title=用户登录
user.username=用户
user.password=密码
user.button.login=登录

user.login.success={0},登录成功
user.not.found=用户不能找到,用户名称=[{0}]         //即显示用户不能找到
user.password.error=密码错误
user.login.error=登录失败

error.exception={0}

 

配置完上面俩个之后,配置当发生异常时,转向的处相应的页面的这个配置,在action标签里有一个属性叫input,通过这个来配置,转到这个属性指向的页面:

input="/login.jsp"

转到这个页面之后,就在这里处理这个异常,由于这个异常信息是存在errorkey里,在这个页面,取出这个异常有俩中方法:

一种是通过<html:errors/>去取,也可以通过<html:messages>标签去取。

<html:messages id="msg" property="error1">
   <bean:write name="msg"/>
  </html:messages>

 

 

 

 

http://xxp3369-126-com.javaeye.com/blog/314617

1、编程式异常
* 截获异常
* 创建相应的异常消息
* 传递异常消息
* 转向相应的页面处理异常
2、声明式异常(自动处理的异常)
* 在struts-config.xml文件中配置<exeception/>标签
* 理解局部和全局exception
* 注意局部<exception/>标签需要配置到<forward/>标签的前面,详见dtd中的约束

<exeception/>标签中的属性说明:
* key:指异常信息对应的国际化消息文本,这个key值需要在国际化资源文件中定义
* type: 处理那种异常
* path: 定义一但出现异常,需要转向那个页面,如果不定义path,
         默认情况下将使用<action>标签中input属性对应的页面
* scope:可以取值request和session,默认为request
* handler:异常的处理类,struts默认采用org.apache.struts.action.ExceptionHandler,
            如果做个性化的异常处理可以继承此类覆写相应的方法
           
参见:ErrorCodeExceptionHandler.java和AppExceptionHandler.java
           


struts-config.xml


Java代码 复制代码
  1. <?xml version="1.0" encoding="ISO-8859-1" ?>   
  2.   
  3. <!DOCTYPE struts-config PUBLIC   
  4.           "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"  
  5.           "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">   
  6.   
  7. <struts-config>   
  8.   
  9.     <form-beans>   
  10.         <form-bean name="loginForm" type="com.bjsxt.struts.LoginActionForm"/>   
  11.     </form-beans>   
  12.        
  13.     <global-exceptions>   
  14.     <!--    
  15.             <exception key="user.not.found" type="com.bjsxt.struts.UserNotFoundException" path="/login_error.jsp"/>   
  16.             <exception key="user.password.error" type="com.bjsxt.struts.PasswordErrorException" path="/login_error.jsp"/>   
  17.      -->   
  18.         
  19.      <!--    
  20.         <exception key="user.not.found" type="com.bjsxt.struts.UserNotFoundException" handler="org.apache.struts.action.ExceptionHandler"/>   
  21.         <exception key="user.password.error" type="com.bjsxt.struts.PasswordErrorException" handler="org.apache.struts.action.ExceptionHandler"/>   
  22.      -->   
  23.         
  24.      <!--    
  25.      <exception key="error.exception" type="com.bjsxt.struts.ErrorCodeException" handler="com.bjsxt.struts.ErrorCodeExceptionHandler"/>   
  26.       -->   
  27.       <!--    
  28.       <exception key="error.exception" type="com.bjsxt.struts.AppException" handler="com.bjsxt.struts.AppExceptionHandler"/>   
  29.        -->      
  30.          
  31.       <exception key="error.exception" type="com.bjsxt.struts.AppException"/>    
  32.     </global-exceptions>   
  33.            
  34.     <action-mappings>   
  35.         <action path="/login"  
  36.                 type="com.bjsxt.struts.LoginAction"  
  37.                 name="loginForm"  
  38.                 scope="request"  
  39.                 validate="false"  
  40.                 input="/login.jsp"  
  41.         >       
  42.         <!--    
  43.             <exception key="user.not.found" type="com.bjsxt.struts.UserNotFoundException" path="/login_error.jsp"/>   
  44.             <exception key="user.password.error" type="com.bjsxt.struts.PasswordErrorException" path="/login_error.jsp"/>   
  45.          -->    
  46.             <forward name="success" path="/login_success.jsp"/>   
  47.             <forward name="error" path="/login.jsp"/>   
  48.         </action>   
  49.            
  50.         <action path="/changelang"  
  51.                 type="com.bjsxt.struts.ChangeLanguageAction"  
  52.         >   
  53.             <forward name="index" path="/index.jsp"/>   
  54.         </action>   
  55.            
  56.         <action path="/login1"  
  57.                 type="org.apache.struts.actions.ForwardAction"  
  58.                 parameter="/login.jsp"  
  59.         ></action>   
  60.     </action-mappings>   
  61.        
  62.     <message-resources parameter="res.MessageResources" />   
  63. </struts-config>  




login.jsp


Java代码 复制代码
  1. <%@ page language="java" contentType="text/html; charset=GB18030"  
  2.     pageEncoding="GB18030"%>   
  3. <%@ taglib prefix="bean" uri="http://struts.apache.org/tags-bean"%>     
  4. <%@ taglib prefix="html" uri="http://struts.apache.org/tags-html" %>     
  5. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">   
  6. <html>   
  7. <head>   
  8. <meta http-equiv="Content-Type" content="text/html; charset=GB18030">   
  9. <title><bean:message key="user.title"/></title>   
  10. </head>   
  11. <body>   
  12.     <h1><bean:message key="user.title"/></h1>   
  13.     <hr>   
  14.     <!--    
  15.     <font color="red">   
  16.         <html:messages id="msg" property="error1">   
  17.             <bean:write name="msg"/>   
  18.         </html:messages>   
  19.     </font>      
  20.     <font color="blue">   
  21.         <html:messages id="msg" property="error2">   
  22.             <bean:write name="msg"/>   
  23.         </html:messages>   
  24.     </font>      
  25.      -->   
  26.      <html:errors/>   
  27.     <form action="login.do" method="post">   
  28.         <bean:message key="user.username"/>:<input type="text" name="username"><br>   
  29.         <bean:message key="user.password"/>:<input type="password" name="password"><br>   
  30.         <input type="submit" value="<bean:message key="user.button.login"/>">   
  31.     </form>   
  32. </body>   
  33. </html>  




login_success.jsp


引用
<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<%@ taglib prefix="bean" uri="http://struts.apache.org/tags-bean"%>
<%@ taglib prefix="html" uri="http://struts.apache.org/tags-html" %>      
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title></title>
</head>
<body>
<html:messages id="msg" message="true" property="loginSuccess1">
<bean:write name="msg"/>
</html:messages>
</body>
</html>




login_error.jsp



Java代码 复制代码
  1. <%@ page language="java" contentType="text/html; charset=GB18030"  
  2.     pageEncoding="GB18030"%>   
  3. <%@ taglib prefix="bean" uri="http://struts.apache.org/tags-bean"%>   
  4. <%@ taglib prefix="html" uri="http://struts.apache.org/tags-html" %>          
  5.       
  6. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">   
  7. <html>   
  8. <head>   
  9. <meta http-equiv="Content-Type" content="text/html; charset=GB18030">   
  10. <title></title>   
  11. </head>   
  12. <body>   
  13.     <font color="red">   
  14.     <!--    
  15.     <li>   
  16.         <html:messages id="msg" property="error1">   
  17.             <bean:write name="msg"/>   
  18.         </html:messages>   
  19.     </li>   
  20.     </font>      
  21.     <font color="blue">   
  22.     <li>   
  23.         <html:messages id="msg" property="error2">   
  24.             <bean:write name="msg"/>   
  25.         </html:messages>   
  26.     </li>    
  27.     </font>      
  28.      -->   
  29.      <html:errors/>   
  30. </body>   
  31. </html>  




login_jstl.jsp


Java代码 复制代码
  1. <%@ page language="java" contentType="text/html; charset=GB18030"  
  2.     pageEncoding="GB18030"%>   
  3. <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>   
  4. <fmt:setLocale value="${header['accept-language']}"/>   
  5. <fmt:setBundle basename="res.MessageResources"/>   
  6. <html>   
  7. <head>    
  8. <meta http-equiv="Content-Type" content="text/html; charset=GB18030">   
  9. <title><fmt:message key="user.title"/></title>   
  10. </head>   
  11. <body>   
  12.     <h1><fmt:message key="user.title"/></h1>   
  13.     <hr>   
  14.     <form action="login.do" method="post">   
  15.         <fmt:message key="user.username"/>:<input type="text" name="username"><br>   
  16.         <fmt:message key="user.password"/>:<input type="password" name="password"><br>   
  17.         <input type="submit" value="<fmt:message key="user.button.login"/>">   
  18.     </form>   
  19. </body>   
  20. </html>  





UserManager.java


Java代码 复制代码
  1. package com.bjsxt.struts;   
  2.   
  3. public class UserManager {   
  4.   
  5.     private static UserManager instance = new UserManager();   
  6.        
  7.     private UserManager() {}   
  8.        
  9.     public static UserManager getInstance() {   
  10.         return instance;   
  11.     }   
  12.        
  13. //  public void login(String username, String password) {   
  14. //      if (!"admin".equals(username)) {   
  15. //          throw new UserNotFoundException(username);   
  16. //      }   
  17. //      if (!"admin".equals(password)) {   
  18. //          throw new PasswordErrorException();   
  19. //      }   
  20. //  }   
  21.   
  22. //  public void login(String username, String password) {   
  23. //      if (!"admin".equals(username)) {   
  24. //          throw new ErrorCodeException("user.not.found", username);   
  25. //      }   
  26. //      if (!"admin".equals(password)) {   
  27. //          throw new ErrorCodeException("user.password.error");   
  28. //      }   
  29. //  }   
  30.   
  31.     public void login(String username, String password) {   
  32.         if (!"admin".equals(username)) {   
  33.             throw new AppException("用户不能找到,用户=【" + username + "】");   
  34.         }   
  35.         if (!"admin".equals(password)) {   
  36.             throw new AppException("密码不正确!");   
  37.         }   
  38.     }   
  39.        
  40. }  




AppException.java


Java代码 复制代码
  1. package com.bjsxt.struts;   
  2.   
  3. public class AppException extends RuntimeException {   
  4.        
  5.     public AppException(String msg) {   
  6.         super(msg);   
  7.     }   
  8. }  



AppExceptionHandler.java


Java代码 复制代码
  1. package com.bjsxt.struts;   
  2.   
  3. import javax.servlet.ServletException;   
  4. import javax.servlet.http.HttpServletRequest;   
  5. import javax.servlet.http.HttpServletResponse;   
  6.   
  7. import org.apache.struts.Globals;   
  8. import org.apache.struts.action.ActionForm;   
  9. import org.apache.struts.action.ActionForward;   
  10. import org.apache.struts.action.ActionMapping;   
  11. import org.apache.struts.action.ActionMessage;   
  12. import org.apache.struts.action.ExceptionHandler;   
  13. import org.apache.struts.config.ExceptionConfig;   
  14. import org.apache.struts.util.ModuleException;   
  15.   
  16. public class AppExceptionHandler extends ExceptionHandler {   
  17.        
  18.        public ActionForward execute(   
  19.                 Exception ex,   
  20.                 ExceptionConfig ae,   
  21.                 ActionMapping mapping,   
  22.                 ActionForm formInstance,   
  23.                 HttpServletRequest request,   
  24.                 HttpServletResponse response)   
  25.                 throws ServletException {   
  26.                    
  27.                 if (!(ex instanceof AppException)) {   
  28.                     return super.execute(ex, ae, mapping, formInstance, request, response);   
  29.                 }   
  30.                    
  31.                 ActionForward forward = null;   
  32.                 ActionMessage error = null;   
  33.                 String property = null;   
  34.   
  35.                 // Build the forward from the exception mapping if it exists   
  36.                 // or from the form input   
  37.                 if (ae.getPath() != null) {   
  38.                     forward = new ActionForward(ae.getPath());   
  39.                 } else {   
  40.                     forward = mapping.getInputForward();   
  41.                 }   
  42.   
  43.                 // Figure out the error   
  44.                 if (ex instanceof ModuleException) {   
  45.                     error = ((ModuleException) ex).getActionMessage();   
  46.                     property = ((ModuleException) ex).getProperty();   
  47.                 } else {   
  48.                     AppException appe = (AppException)ex;   
  49.                     error = new ActionMessage(ae.getKey(), appe.getMessage());   
  50.                     property = error.getKey();   
  51.                        
  52.                     //error = new ActionMessage(ae.getKey(), ex.getMessage());   
  53.                     //property = error.getKey();   
  54.                 }   
  55.   
  56.                 this.logException(ex);   
  57.   
  58.                 // Store the exception   
  59.                 request.setAttribute(Globals.EXCEPTION_KEY, ex);   
  60.                 this.storeException(request, property, error, forward, ae.getScope());   
  61.   
  62.                 return forward;   
  63.   
  64.             }      
  65. }  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2009-03-13 20:59  刘阳  阅读(355)  评论(0编辑  收藏  举报