异常处理实现方法:
1. 自定义一个异常类 extends Exception
2. 定义一个异常错误的jsp页面,例如:505.jsp
3. 自定义一个全局异常类实现接口HandlerExceptionResolver
重载函数resolveException
实现逻辑:
a. 当异常为自定义异常的时候,把消息设置到自定义的异常类的消息中
b.当异常非自定义异常的时候,则构造一个自定义的异常类型
c.跳转到错误页面
4. 配置Spring MVC配置文件中使用自定义的全局类
<beanclass="cn.itcast.ssm.exception.CustomHandlerExceptionResolver"/>
自定义异常类
package cn.itcast.ssm.exception;
public class CustomException extends Exception {
private String message;
public CustomException(String message){
super(message);
this.message = message;
}
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
自定义全局异常处理类
package cn.itcast.ssm.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 CustomHandlerExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
/*
解析出异常类型
如果该 异常类型是系统 自定义的异常,直接取出异常信息,在错误页面展示
如果该 异常类型不是系统 自定义的异常,构造一个自定义的异常类型(信息为“未知错误”)
}*/
CustomException customException = null;
if( ex instanceof CustomException){
customException = (CustomException)ex;
}else{
customException = new CustomException("位置的错误:"+ex.getMessage());
}
//错误信息
String errorMsg = customException.getMessage();
ModelAndView modelAndView= new ModelAndView();
modelAndView.addObject("message", errorMsg);
modelAndView.setViewName("500");
return modelAndView;
}
}
500.jsp页面
<%--
Created by IntelliJ IDEA.
User: duoduo
Date: 2017/3/26
Time: 10:56
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Error Msg</title>
</head>
<body>
${message}
</body>
</html>