天天看點

struts2異常攔截器

      在實際開發中,我們需要将捕獲的異常資訊列印出來,換上通俗的語言讓客戶能夠大概了解是原因引起的異常,是以我們需要将異常資訊顯示到頁面上來,讓客戶能夠看得見。這裡介紹以下struts2的異常處理機制。在sturts2的struts-default.xml中,引用了struts2定義的攔截器:

  <interceptor name="exception" class="com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor"/>

下面是一個小例子來說明struts2中,應該如何捕獲異常資訊,并将異常資訊顯示到頁面:

一個簡單的index.jsp頁面,隻有一個按鈕,點選進入action:

<s:form action="login">

           <s:submit value="submit"/>

 </s:form>

struts.xml的配置:

< struts >

  < package   name ="Action"  extends ="struts-default" >

     < global-results >

      < result  name ="all" > /error.jsp </ result >

     </ global-results >

     < global-exception-mappings >   

                  < exception-mapping  result ="all"  exception ="java.lang.Exception" >   

                  </ exception-mapping >

     </ global-exception-mappings >   

< action  name ="login"  class ="com.action.LoginAction" >

       < result  name ="success" > /success.jsp </ result >

    </ action >

  </ package >

</ struts >

Action:

public   class  LoginAction   extends  ActionSupport   {

    @Override

    public String execute() throws Exception {

    try{    

        int i = 9/0;

    }catch (Exception e) {

        throw new Exception(e);

    }

        return "success";

    }

}

列印錯誤資訊的頁面 error.jsp:

  < body >

     < s:property value = " exception.message " />

   </ body >

這樣就可以把異常資訊列印到指定的頁面,當然也可以在struts.xml中定義局部的異常映射資訊。

繼續閱讀