springmvc异常处理
dao、service、controller都可能出现异常,当出现异常都通过throws Exception向上抛出,最后由SpringMVC前端控制器交由异常处理器进行异常处理,SpringMVC提供全局异常处理器(一个系统只有一个异常处理器)进行统一异常处理。
自定义异常类
public class MyException extends Exception {
private String message;
public MyException(String message) {
this.message = message;
}
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
编写异常处理器
springmvc的异常处理器需要实现HandlerExceptionResolver 接口
public class MyExceptionResolver implements HandlerExceptionResolver {
/**
* 处理异常
* @param request
* @param response
* @param handler
* @param ex 抛出的异常
* @return
*/
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
//获取异常对象
MyException myException = null;
//如果是预期的异常,则获取异常信息
if(ex instanceof MyException){
myException = (MyException) ex;
}else {
//不是预测的异常,则统一为系统维护....
myException = new MyException("系统正在维护...");
}
//创建ModelAndView对象
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("error",myException.getMessage() );
//返回错误提示页面
modelAndView.setViewName("error");
return modelAndView;
}
}
配置异常处理器
<bean id="myException" class="com.lb.exception.MyExceptionResolver"/>
@RequestMapping("/exception")
public String testException() throws Exception {
System.out.println("testException执行了...");
//模拟异常
int i = 1/0;
return "success";
}
@RequestMapping("/exception")
public String testException() throws MyException {
System.out.println("testException执行了...");
//模拟异常
try {
int i = 1/0;
} catch (Exception e) {
e.printStackTrace();
throw new MyException("出错啦...");
}
return "success";
}
Springmvc的处理器拦截器类似于Servlet 开发中的过滤器Filter,用于对处理器进行预处理和后处理。
springmvc的自定义拦截器需要实现HandlerInterceptor 接口,该接口有三个方法,preHandle: 进入controller方法之前执行,postHandle: 进入controller方法之后,返回ModekAndView之前执行,以及afterCompletion: 执行完controller方法之后执行
public class MyInterceptor implements HandlerInterceptor {
/**
* controller处理前执行
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("拦截器执行了...");
return true;
}
/**
* controller处理后执行
* @param request
* @param response
* @param handler
* @param modelAndView
* @throws Exception
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
配置拦截器
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.lb.interceptor.MyInterceptor"/>
mvc:interceptor>
mvc:interceptors>