@ControllerAdvice注解本身已經使用了@Component,是以@ControllerAdvice注解所标注的類将會自動被元件掃描擷取到,就像帶有@Component注解的類一樣。另外,在帶有@ControllerAdvice注解的類中,異常處理會應用到所有控制器中帶有@RequestMapping注解的方法上。
自定義exception:
<code>@ResponseStatus</code><code>(value = HttpStatus.NOT_FOUND,reason = </code><code>"file not found"</code><code>)</code>
<code>public</code> <code>class</code> <code>NotFoundException </code><code>extends</code> <code>RuntimeException {</code>
<code>}</code>
定義ControllerAdvice
<code>@ControllerAdvice</code>
<code>public</code> <code>class</code> <code>GlobalExceptionHandler {</code>
<code> </code><code>@ExceptionHandler</code><code>(NotFoundException.</code><code>class</code><code>)</code>
<code> </code><code>public</code> <code>String NotFoundHandler()</code>
<code> </code><code>{</code>
<code> </code><code>return</code> <code>"error/404.html"</code><code>;</code>
<code> </code><code>}</code>
<code> </code><code>@ExceptionHandler</code><code>(Exception.</code><code>class</code><code>)</code>
<code> </code><code>public</code> <code>String ErrorHandler(){</code>
<code> </code><code>return</code> <code>"error/error.html"</code><code>;</code>
錯誤頁controller
<code>@RequestMapping</code><code>(</code><code>"/error404"</code><code>)</code>
<code> </code><code>public</code> <code>String error(){</code>
<code> </code><code>throw</code> <code>new</code> <code>NotFoundException();</code>
<code> </code><code>@RequestMapping</code><code>(</code><code>"/error"</code><code>)</code>
<code> </code><code>public</code> <code>String errorNotFound() </code><code>throws</code> <code>Exception {</code>
<code> </code><code>throw</code> <code>new</code> <code>Exception();</code>
view:
在views/error目錄下新增error.html和404.html
http://localhost:8092/category/error404
http://localhost:8092/category/error
<a href="http://viralpatel.net/blogs/spring-mvc-exception-handling-controlleradvice-annotation/" target="_blank">http://viralpatel.net/blogs/spring-mvc-exception-handling-controlleradvice-annotation/</a>
本文轉自 陳敬(Cathy) 部落格園部落格,原文連結:http://www.cnblogs.com/janes/p/6933958.html,如需轉載請自行聯系原作者