1. 程式人生 > >springmvc學習筆記(33)——SimpleMappingExceptionResolver異常對映 XML檔案配置

springmvc學習筆記(33)——SimpleMappingExceptionResolver異常對映 XML檔案配置

SimpleMappingException異常對映
當異常發生時,我們可以將它對映到我們指定的介面

在springmvc中配置

 

 <!-- 配置使用 SimpleMappingExceptionResolver 來對映異常 -->
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <!-- 
        配置異常的屬性值為ex,那麼在錯誤頁面中可以通過 ${ex} 來獲取異常的資訊
        如果不配置這個屬性,它的預設值為exception
         -->
        <property name="exceptionAttribute" value="ex"></property>
        <property name="exceptionMappings">
            <props>
                <!-- 對映ArrayIndexOutOfBoundsException異常對應error.jsp這個頁面 -->
                <prop key="java.lang.ArrayIndexOutOfBoundsException">error</prop>
            </props>
        </property>
    </bean> 


寫個目標方法測試一下

   

 @RequestMapping("/testExceptionMapping")
    public String testExceptionMapping(){
        int arrays[] = new int[10];
        System.out.println(arrays[11]);
        return "hello";
    }

這裡將發生陣列下標越界的異常,訪問目標方法,得到如下結果 


error.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
${ex }
</body>
</html>