3.3 HandlerExceptionResolver
需要编写一个自定义的异常类。
3.3.1 前台页面
示例:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>HandlerExceptionResolver处理异常</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/exception/test3.action">HandlerExceptionResolver处理异常</a>
</body>
</html>
3.3.2 ExceptionController中模拟异常
示例:
/**
* 异常处理方法
*/
@RequestMapping("/test3")
public String test3(){
System.out.println("ExceptionController的test3");
// 模拟异常 java.lang.ArrayIndexOutOfBoundsException
int[] array = new int[2];
array[2] = 10;
return "success";
}
3.3.3 编写一个自定义异常类
示例:
package com.marshal.study.springmvc.exception;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.StringWriter;
public class MyHandlerExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
Object o,
Exception ex) {
// 取出异常栈信息
StringWriter writer = new StringWriter();
PrintWriter s = new PrintWriter(writer);
ex.printStackTrace(s);
ModelAndView mav = new ModelAndView();
mav.addObject("error",writer.toString());
mav.setViewName("error");
return mav;
}
}
3.3.4 配置dispatcher-servlet.xml文件
只需要构造一个自定义异常类的对象,并让其生效就可以了。
示例:
<bean class="com.marshal.study.springmvc.exception.MyHandlerExceptionResolver"></bean>
运行结果如下图所示: