异常处理的思路
在SpringMVC项目中,Controller调用service,service调用dao,若出现异常,异常都是向上抛出的,最终是由DispatcherServlet找HandlerExceptionResolver进行异常处理。
示例代码
编写jsp代码
<%@page contentType="text/html; charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>requestMapping的使用</title>
</head>
<body>
<h3>实现异常处理器接口 处理异常</h3>
<a href="testException">测试异常处理</a>
</body>
</html>
编写异常类
package com.liang.exception;
/**
* 自定义异常处理类
*/
public class CustomException extends Exception {
private String message;
public CustomException(String message) {
this.message = message;
}
public String getMessage()
{
return message;
}
}
自定义异常处理器
package com.liang.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 CustomExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
e.printStackTrace();
CustomException customException = null;
if(e instanceof CustomException){
customException = (CustomException) e;
}else{
customException = new CustomException("系统错误,请与系统管理员联系!!!");
}
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("message",customException.getMessage());
modelAndView.setViewName("exception");
return modelAndView;
}
}
编写异常处理友好页面(exception.jsp)
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>执行失败</title>
</head>
<body>
执行失败!!!<br/>
${message}
</body>
</html>
配置自定义处理器(SpringMVC配置文件)
<!--配置自定义异常处理器-->
<bean id="customExceptionResolver" class="com.liang.exception.CustomExceptionResolver"></bean>