1.关于@ControllerAdvice
@ControllerAdvice注解本身已经使用了@Component,因此@ControllerAdvice注解所标注的类将会自动被组件扫描获取到,就像带有@Component注解的类一样。另外,在带有@ControllerAdvice注解的类中,异常处理会应用到所有控制器中带有@RequestMapping注解的方法上。
2.使用示例
自定义exception:
1
2
3
|
@ResponseStatus
(value = HttpStatus.NOT_FOUND,reason =
"file not found"
)
public
class
NotFoundException
extends
RuntimeException {
}
|
定义ControllerAdvice
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
@ControllerAdvice
public
class
GlobalExceptionHandler {
@ExceptionHandler
(NotFoundException.
class
)
public
String NotFoundHandler()
{
return
"error/404.html"
;
}
@ExceptionHandler
(Exception.
class
)
public
String ErrorHandler(){
return
"error/error.html"
;
}
}
|
错误页controller
1
2
3
4
5
6
7
8
9
|
@RequestMapping
(
"/error404"
)
public
String error(){
throw
new
NotFoundException();
}
@RequestMapping
(
"/error"
)
public
String errorNotFound()
throws
Exception {
throw
new
Exception();
}
|
view:
在views/error目录下新增error.html和404.html
3.测试
http://localhost:8092/category/error404
http://localhost:8092/category/error
4.参考资料推荐
http://viralpatel.net/blogs/spring-mvc-exception-handling-controlleradvice-annotation/
本文转自 陈敬(Cathy) 博客园博客,原文链接:http://www.cnblogs.com/janes/p/6933958.html,如需转载请自行联系原作者