ExceptionTestController.java
/**
* 告诉SpringMVC这个方法专门处理这个类发生的异常 1、给方法上随便写一个Exception,用来接受发生的异常
* 2、要携带异常信息不能给参数位置写Model; 3、返回ModelAndView就行了;
* 4、如果有多个@ExceptionHandler都能处理这个异常,精确优先 5、全局异常处理与本类同时存在,本类优先;
*/
@ExceptionHandler(value = { Exception.class })
public ModelAndView handleException01(Exception exception) {
System.out.println("本类的:handleException01..." + exception);
//
ModelAndView view = new ModelAndView("myerror");
view.addObject("ex", exception);
// 视图解析器拼串
return view;
}
myerror.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>
<h1>出错啦!</h1>
<h2>错误信息:${ex }</h2>
</body>
</html>
index.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>
<%
pageContext.setAttribute("ctp", request.getContextPath());
%>
</head>
<body>
<a href="${ctp }/handle01?i=10">test01-哈哈</a><br/>
</body>
</html>
出现异常,会根据ExceptionTestController中的方法返回到指定页面,并返回错误信息。