SpringMVC异常处理

原理:


思路:

  1. 自定义异常类
package cn.itcast.exception;
public class SysException extends Exception{
   
private static final long serialVersionUID = 4055945147128016300L;
// 异常提示信息
private String message;
public String getMessage() {
   
return message;
}
public void setMessage(String message) {
   
this.message = message;
}
public SysException(String message) {
   
this.message = message;
}

错误页面:
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>执行失败</title>
</head>
<body>
执行失败!
${message }
</body>
</html>
  1. 自定义异常处理器
package cn.itcast.exception;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
/** * 异常处理器 * @author rt */
public class SysExceptionResolver implements HandlerExceptionResolver{
   
/** * 跳转到具体的错误页面的方法 */
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse
response, Object handler,
Exception ex) {
   
ex.printStackTrace();
SysException e = null;
// 获取到异常对象
if(ex instanceof SysException) {
   
e = (SysException) ex;
}else {
   
e = new SysException("请联系管理员");
}
ModelAndView mv = new ModelAndView();
// 存入错误的提示信息
mv.addObject("message", e.getMessage());
// 跳转的Jsp页面
mv.setViewName("error");
return mv;
}
}
  1. 配置异常处理器
<!-- 配置异常处理器 -->
<bean id="sysExceptionResolver" class="cn.itcast.exception.SysExceptionResolver"/>
  1. 运行结果:
全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务