近幾天又溫習了一下SpringMVC的運行機制以及原理
我理解的springmvc,是設計模式MVC中C層,也就是Controller(控制)層,常用的注解有@Controller、@RequestMapping、@Autowared、@Component,今天呢,我所要寫的是SpringMVC的全局異常處理器,關聯的接口有HandlerExceptionResolver(Eclipse用戶可以按Ctrl+Shift+T進行搜索該接口),什么是全局異常處理器?為什么要用它呢?
在企業開發中,各種的Runtime異常可能會讓我們崩潰,但是還有一部分異常在此之外,因此我們就要捕獲它,然后進行操作提示(將錯誤提示返回到ModelAndView)
下來呢,我貼一部分代碼
首先呢,創建一個自定義的異常類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
/** * @Title: ExceptionCustom.java * @Description: 本地異常 * @author ChoviWu * @version V1.0 */ public class ExceptionCustom extends Exception{ /** * @Fields serialVersionUID : */ private static final long serialVersionUID = 1L; private String message; /** * @return the message */ public String getMessage() { return message; } /** * @param message the message to set */ public void setMessage(String message) { this .message = message; } public ExceptionCustom() { super (); // TODO Auto-generated constructor stub } public ExceptionCustom(String message) { super (message); this .message = message; } } |
創建一個全局異常處理器的類,讓它實現HandlerExceptionResolver 接口。相信,基礎好一點的同學可以看出來我代碼的意思(注釋)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; /** * @Title: SimpleException.java * @Description:全局異常處理器 * @author ChoviWu * @version V1.0 */ public class SimpleExceptionResolver implements HandlerExceptionResolver { // 異常對象 ExceptionCustom exceptionCustom = null ; private Logger logger = Logger.getLogger(SimpleExceptionResolver. class .getSimpleName()); /** * 全局處理異常 */ public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { //轉化為自定義異常 exceptionCustom = (ExceptionCustom) ex; //判斷是否是本地異常 if (ex instanceof ExceptionCustom) { logger.info(ex.getMessage()); } else { …拋出錯誤 } //獲取異常信息 String message = exceptionCustom.getMessage(); ModelAndView mv = new ModelAndView(); //將異常返回到Model mv.addObject( "xx" , message); // 指向錯誤頁面 mv.setViewName( "error" ); return null ; } } |
解釋一下,在判斷一個異常是否是其他異常的時候,先看它是否屬于本地異常(Exception)的exceptionCustom ,如果是本地異常,則拋出本地異常信息
1
2
3
4
5
|
if (ex instanceof ExceptionCustom) { logger.info(ex.getMessage()); } else { …拋出錯誤 } |
如果不是本地異常,則拋出未知異常
然后從異常里面獲取異常信息,將異常信息返回到MV中,最后轉至頁面,當然嚴謹一點的,會將異常信息添加到數據庫中,方便查看
由于本文章只是一個Demo,所以沒有考慮到很多因素
下來,說說配置文件
配置文件,先貼上代碼,然后再做解釋
1
2
|
<!-- 全局異常處理器 --> <bean id= "handlerExceptionResolver" class = "xxxx(包名).SimpleExceptionResolver" /> |
注意:首先,這個bean將配置在自己的web層.xml(spring-web.xml),當啟動tomcat,加載web.xml后需加載spring-web.xml
之前注入的bean的id我隨便寫了一個名稱,然后spring解析的時候報錯了,
之后看了源碼的時候,才知道原來是這么回事
1
2
|
1SpringMVC 在org.springframework.web.servlet.DispatcherServlet類中聲明了 public static final String HANDLER_EXCEPTION_RESOLVER_BEAN_NAME = "handlerExceptionResolver" ; |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
private void initHandlerExceptionResolvers(ApplicationContext context) { this .handlerExceptionResolvers = null ; if ( this .detectAllHandlerExceptionResolvers) { // Find all HandlerExceptionResolvers in the ApplicationContext, including ancestor contexts. Map<String, HandlerExceptionResolver> matchingBeans = BeanFactoryUtils .beansOfTypeIncludingAncestors(context, HandlerExceptionResolver. class , true , false ); if (!matchingBeans.isEmpty()) { this .handlerExceptionResolvers = new ArrayList<HandlerExceptionResolver>(matchingBeans.values()); // We keep HandlerExceptionResolvers in sorted order. OrderComparator.sort( this .handlerExceptionResolvers); } } else { try { HandlerExceptionResolver her = context.getBean(HANDLER_EXCEPTION_RESOLVER_BEAN_NAME, HandlerExceptionResolver. class ); this .handlerExceptionResolvers = Collections.singletonList(her); } catch (NoSuchBeanDefinitionException ex) { // Ignore, no HandlerExceptionResolver is fine too. } } |
看完這段代碼的同學應該就知道為什么把bean 的id 設置成handlerExceptionResolver了吧
1
|
HandlerExceptionResolver her =context.getBean(HANDLER_EXCEPTION_RESOLVER_BEAN_NAME, HandlerExceptionResolver. class ); |
所以說,全局異常處理器的bean的id不能隨便的設置。
以上這篇基于SpringMVC的全局異常處理器介紹就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。