(11)ExceptionMapping

当因为某些原因。发生异常时,可以对异常进行捕获,给用户友好的界面
下面的例子就是当Action发生异常后,因为result就是按照excute返回值来确定跳转到哪个页面的,所以在Action中可以返回success,这时异常抛给struct.xml,若写
exception-mapping 相当于接收到了异常,让这个mapping指向应该去哪个页面。在去往的异常页面中,可以友好的简单提示出错信息。也可以通过ognl获取exceptionStack信息,方便以后系统的改进。
与global-result相似,也有global-exception-mappings。
struct.xml

  <struts>
   <!-- 局部异常映射与全局异常映射  局部result与全局result -->
  <package name="ExceptionMapping" namespace="/ExceptionMapping" extends="struts-default">
     <global-results>
        <result name="array-exception">/error1.jsp</result>
     </global-results>
     <global-exception-mappings>
        <exception-mapping result="array-exception" exception="java.lang.ArrayIndexOutOfBoundsException"></exception-mapping>
     </global-exception-mappings>
     <action name="test" class="com.action.UserAction" >
     <exception-mapping result="math-exception" exception="java.lang.ArithmeticException"></exception-mapping>
         <result name="math-exception">/error.jsp</result>
         <result>/welcome.jsp</result>
     </action>

    </package>

</struts>

UserAction

public class UserAction extends ActionSupport{



    public String execute() throws Exception {
        //int a=5/0;

        int a[]={1,2};
        for(int i=0;i<=a.length;i++){
            System.out.println(a[i]);
        }

        return SUCCESS;//若执行,必然会抛出除数为0的错误,这个错误是RuntimeException,该函数并没有做处理,则会抛给struct2取处理
        //struct2也没进行处理,就会抛给web容器,在实际开发中,不能这样的异常页面显示给用户,一种简单的处理方法是跳转到下一个错误处理页面
    }

}

error1.jsp

 <body>
   数组下标越界
   <hr/>
   <font color="red">错误信息如下:</font><br/>
   <!--输出一句话只是简单的处理,,其实可以将具体的异常信息展示出来,根据值栈中显示的信息,可以展示 -->
   <s:property value="exceptionStack"/>
   <s:debug></s:debug>
  </body>
posted @ 2017-11-07 10:47  测试开发分享站  阅读(85)  评论(0编辑  收藏  举报