A:全局异常处理
定义一个异常处理类
注意:不要忘记交给spring管理–@Controller
//实现了HandlerExceptionResolver接口
@Controller
public class ExceptionHandlerResolver implements HandlerExceptionResolver{
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse, Object object,
Exception exception) {
String message=exception.getMessage();
ModelAndView modelAndView=new ModelAndView();
modelAndView.addObject("message", message);
modelAndView.setViewName("/error.jsp");
return modelAndView;
}
}
B:同一个controller中的异常处理
//使用@ExceptionHandler 注解
@ExceptionHandler
public ModelAndView exception(Exception exception){
ModelAndView modelAndView=new ModelAndView();
modelAndView.addObject("message", exception.getMessage());
modelAndView.setViewName("/error.jsp");
return modelAndView;
}
@RequestMapping("/test6")
public String test6() throws Exception{
int i=5/0;
System.out.println("====");
return "redirect:/index.jsp";
}