SpringMvc 全局异常处理
MyExceptionHandler
package exception; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.servlet.ModelAndView; @ControllerAdvice public class MyExceptionHandler {//不是控制器,仅仅是 用于处理异常的类 @ExceptionHandler(Exception.class) public ModelAndView handlerArithmeticException2(Exception e) { ModelAndView mv = new ModelAndView("error"); System.out.println(e + "============" + "该@ControllerAdvice中的异常处理方法,可以处理任何类中的异常"); mv.addObject("er", e); return mv; } }
SecondSpringMVCHandler
package handler; import exception.MyArrayIndexOutofBoundsException; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseStatus; @Controller @RequestMapping("second") public class SecondSpringMVCHandler { @RequestMapping("testExceptionHandler") public String testExceptionHandler() { System.out.println(1 / 0); return "success"; } @RequestMapping("testExceptionHandler2") public String testExceptionHandler2() { int[] nums = new int[2]; System.out.println(nums[2]);//ArrayIndexOutOfBoundsException return "success"; } }
component-scan
<context:component-scan base-package="exception"></context:component-scan>
error.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>Insert title here</title> </head> <body> ${requestScope.er } </body> </html>