- 如果希望对所有异常进行统一处理,可以使用SimpleMappingExceptionResolver,它将异常类名映射为视图名,即发生异常时使用对应的视图报告异常
第一步:index.jsp下写一个< a>标签
<a href="testSimpleMappingExceptionResolver?i=2">Test SimpleMappingExceptionResolver</a>
第二步:写handler响应方法
@RequestMapping("/SimpleMappingExceptionResolver")
public String testSimpleMappingExceptionResolver(@RequestParam("i") int i){
String[] vals = new String[10];
System.out.println(vals[i]);
return "success";
}
注意,http://localhost:8080/springmvc-2/testSimpleMappingExceptionResolver?i=20
这里的i>=10的话会报数组越界的exception
第三步:配置使用SimpleMappingExceptionResolver 来映射异常
<!--配置使用SimpleMappingExceptionResolver 来映射异常-->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="java.lang.ArrayIndexOutOfBoundsException">error</prop>
</props>
</property>
</bean>
配置里面的error,意味着会跳转到error界面
error.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h4>Error Page</h4>
${requestScope.exception}
</body>
</html>
tips:
<!--配置使用SimpleMappingExceptionResolver 来映射异常-->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionAttribute" value="ex"></property>
<property name="exceptionMappings">
<props>
<prop key="java.lang.ArrayIndexOutOfBoundsException">error</prop>
</props>
</property>
</bean>
则error.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h4>Error Page</h4>
${requestScope.ex}
</body>
</html>