1.在index.jsp中写一个a标签
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>index页面</h3>
<a href="user/testException">testException</a>
</body>
</html>
2.在UserController中写testException方法
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/testException")
public String testException(){
System.out.println("testException执行了");
//模拟异常
int a=10/0;
return "success";
}
}
3.部署,提示错误
4.编写自定义异常类
package cn.itcast.exception;
/**
* 自定义异常类
*/
public class SysException extends Exception{
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public SysException(String message) {
this.message = message;
}
}
5.在UserController中修改testException方法
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/testException")
public String testException() throws SysException {
System.out.println("testException执行了");
try{
//模拟异常
int a=10/0;
}catch (Exception e){
//打印异常信息
e.printStackTrace();
//抛出自定义异常信息
throw new SysException("出现错误");
}
return "success";
}
}
6.编写异常处理器类
package cn.itcast.exception;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SysExceptionResolver implements HandlerExceptionResolver {
@Override
/**
* 处理异常业务逻辑
*/
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception ex) {
//获取到异常对象
SysException e=null;
if (ex instanceof SysException){
e=(SysException)ex;
}else{
e=new SysException("系统正在维护");
}
//创建ModelAndView对象
ModelAndView mv=new ModelAndView();
mv.addObject("errorMsg",e.getMessage());
mv.setViewName("error");
return mv;
}
}
7.在springmvc.xml中配置异常处理器
<!--配置异常处理器-->
<bean id="sysExceptionResolver" class="cn.itcast.exception.SysExceptionResolver"></bean>
8.写一个error.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${errorMsg}
</body>
</html>
9.重新部署