异常处理方式:
1. 配置简单异常处理器SimpleMappingExceptionResolver
2. 自定义异常处理器
1. 配置简单异常处理器
首先写一段有类型转换错误的代码
@Controller
public class DemoController {
@RequestMapping("/show")
public void show(){
Object s = "fsfs";
Integer i = (Integer)s;
}
}
去spring-mvc.xml配置SpringMVC提供的简单异常处理器,这里只是测试一下类型转换异常,至于error则是通过配置视图解析器转换成相应的资源路径。
<!-- 配置异常处理器-->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<map>
<entry key="java.lang.ClassCastException" value="error"/>
</map>
</property>
</bean>
创建一个error.jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>类型转换异常</h1>
</body>
</html>
测试一下,当出现 java.lang.ClassCastException 可以跳转到相应的页面error.jsp
2. 自定义异常处理器
设计一个自定义异常类实现异常接口,单纯创建
public class MyException extends Exception {
}
然后在设计一个方法去测试该异常
@RequestMapping("/show1")
public void show1() throws MyException {
throw new MyException();
}
然后创建异常处理器类实现HandlerExceptionResolver
package cn.resolver;
import cn.leohams.exception.MyException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
ModelAndView mv = new ModelAndView();
if (e instanceof MyException){
mv.addObject("msg", "自定义异常");
mv.setViewName("error1");
}else {}
return mv;
}
}
在Spring-mvc.xml中配置异常处理器,添加bean
<bean class="cn.leohams.resolver.MyExceptionResolver"/>
编写error1.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>${msg}</h1>
</body>
</html>
测试能否异常跳转