1. 程式人生 > >springMVC3學習(八)--全域性的異常處理

springMVC3學習(八)--全域性的異常處理

在springMVC的配置檔案中:

[html]  view plain  copy   在CODE上檢視程式碼片 派生到我的程式碼片
  1. <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">  
  2.     <
    property name="defaultErrorView">  
  3.         <value>/error</value><!-- 表示當丟擲異常但沒有在exceptionMappings裡面找到對應的異常時 返回名叫error的檢視-->  
  4.     </property>  
  5.     <
    property name="defaultStatusCode" value="404"/><!-- 表示在發生異常時預設的HttpServletResponse的返回碼,預設是404-->  
  6.     <property name="statusCodes"><!-- 定義在發生異常時檢視跟返回碼的對應關係 -->  
  7.         <
    props>  
  8.             <!-- 表示在發生NumberFormatException時返回檢視number,然後這裡定義發生異常時檢視number對應的HttpServletResponse的返回碼是500 -->  
  9.             <prop key="number">500</prop>  
  10.             <prop key="null">503</prop>  
  11.         </props>  
  12.     </property>  
  13.     <property name="exceptionMappings">  
  14.         <props>  
  15.             <prop key="NumberFormatException">number</prop><!-- 表示當丟擲NumberFormatException的時候就返回名叫number的檢視-->  
  16.             <prop key="NullPointerException">null</prop>  
  17.         </props>  
  18.     </property>  
  19. </bean>   

這裡主要的類是SimpleMappingExceptionResolver類,和他的父類AbstractHandlerExceptionResolver類。

你也可以實現HandlerExceptionResolver介面,寫一個自己的異常處理程式.

通過SimpleMappingExceptionResolver我們可以將不同的異常對映到不同的jsp頁面(通過exceptionMappings屬性的配置)。

同時我們也可以為所有的異常指定一個預設的異常提示頁面(通過defaultErrorView屬性的配置),

如果所丟擲的異常在exceptionMappings中沒有對應的對映,則spring將用此預設配置顯示異常資訊。


Login.Java測試類

[java]  view plain  copy   在CODE上檢視程式碼片 派生到我的程式碼片
  1. import java.io.File;  
  2. import org.springframework.stereotype.Controller;  
  3. import org.springframework.web.bind.annotation.RequestMapping;  
  4.   
  5. @Controller  
  6. public class Login {  
  7.     @RequestMapping("/null")  
  8.     public void testNullPointerException() {  
  9.          File file = null;  
  10.          // 空指標異常,返回定義在SpringMVC配置檔案中的null檢視  
  11.          System.out.println(file.getName());  
  12.     }  
  13.   
  14.     @RequestMapping("/number")  
  15.     public void testNumberFormatException() {  
  16.          // NumberFormatException,返回定義在SpringMVC配置檔案中的number檢視  
  17.          Integer.parseInt("abc");  
  18.     }  
  19.   
  20.     @RequestMapping("/default")  
  21.     public void testDefaultException() {  
  22.         if (1 == 1)  
  23.           // 由於該異常型別在SpringMVC的配置檔案中沒有指定,所以就會返回預設的exception檢視  
  24.           throw new RuntimeException("Error!");  
  25.     }  
  26. }  

顯示錯誤的jsp頁面(已error.jsp為例)

[html]  view plain  copy   在CODE上檢視程式碼片 派生到我的程式碼片
  1. <body>  
  2.     <%  
  3.         Exception e = (Exception)request.getAttribute("exception");  
  4.         out.print(e.getMessage());  
  5.     %>  
  6. </body>  

測試URL:   http://localhost:8080/spring_exception/null

            http://localhost:8080/spring_exception/number

            http://localhost:8080/spring_exception/default