简介
@ControllerAdvice注解如果当前Handler中找不到@ExceptionHandler方法来解决当前方法出现的异常,则将去@ControllerAdvice注解标记的类中查找@ExceptionHandler标记的方法来处理异常。
例如(当id = 0时,将出现异常)
index.jsp
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%--
Created by IntelliJ IDEA.
User: 23369
Date: 3/31/2019
Time: 3:03 PM
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<a href="testExceptionHandlerExceptionResolver?id=10">TestExceptionHandlerExceptionResolver</a>
</body>
</html>
error.jsp
<%--
Created by IntelliJ IDEA.
User: 23369
Date: 4/4/2019
Time: 7:50 PM
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
errorPage
<br>
错误信息是:${requestScope.exception}
</body>
</html>
TestException.class
package com.hello2;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class TestException {
/*
若不使用@ControllerAdvice注解,可以直接使用该方式在页面中输出异常信息
@ExceptionHandler({ArithmeticException.class})
public String handlerArithmeticException(Exception exception){
System.out.println("异常" + exception);
return "error";
}
*/
@RequestMapping("testExceptionHandlerExceptionResolver")
public String testExceptionHandlerExceptionResolver(@RequestParam("id") Integer id ){
System.out.println(10/id);
return "success";
}
}
使用 @ControllerAdvice注解
package com.hello2;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
@ControllerAdvice
public class HandlerException {
@ExceptionHandler({ArithmeticException.class})
public ModelAndView handlerArithmeticException(Exception exception){
ModelAndView modelAndView = new ModelAndView("error");
modelAndView.addObject("exception",exception);
return modelAndView;
}
}