1. 程式人生 > >Spring MVC 解析之 DispatcherServlet之異常處理機制HandlerExceptionResolver

Spring MVC 解析之 DispatcherServlet之異常處理機制HandlerExceptionResolver

springMVC對Controller執行過程中出現的異常提供了統一的處理機制,其實這種處理機制也簡單,只要丟擲的異常在DispatcherServlet中都會進行捕獲,這樣就可以統一的對異常進行處理。

springMVC提供了一個HandlerExceptionResolver介面,其定義方法如下:

public interface HandlerExceptionResolver {
 
	/**
	 * Try to resolve the given exception that got thrown during handler execution,
	 * returning a {@link ModelAndView} that represents a specific error page if appropriate.
	 * <p>The returned {@code ModelAndView} may be {@linkplain ModelAndView#isEmpty() empty}
	 * to indicate that the exception has been resolved successfully but that no view
	 * should be rendered, for instance by setting a status code.
	 * @param request current HTTP request
	 * @param response current HTTP response
	 * @param handler the executed handler, or {@code null} if none chosen at the
	 * time of the exception (for example, if multipart resolution failed)
	 * @param ex the exception that got thrown during handler execution
	 * @return a corresponding {@code ModelAndView} to forward to, or {@code null}
	 * for default processing
	 */
	ModelAndView resolveException(
			HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex);
 
}

接下來我們建立一個自己簡單從異常處理類MyHandlerExceptionResolver,實現是非常簡單的,只要實現HandlerExceptionResolver即可,將我們實現的MyHandlerExceptionResolver注入到容器中。

<bean id="myHandlerExceptionResolver" class="com.tianjunwei.handlerExceptionResolver.MyHandlerExceptionResolver"></bean>

public class MyHandlerExceptionResolver implements HandlerExceptionResolver{
 
 
	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		
		ModelAndView mv = new ModelAndView("exception");
		mv.addObject("errorMsg", ex.getMessage());
		return mv;
	}
}

最終結果是返回一個ModelAndView物件,返回頁面是exception.jsp,頁面如下,展示放在errorMsg中的異常資訊。

<%@ 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">
 
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
 
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	${errorMsg} 
</body>
</html>

我們建立一個丟擲異常的Controller,如下:

@Controller
public class ExceptionController {
	
	@RequestMapping("/exception")
	public String exception() throws Exception{
			throw new Exception("發生異常了");
	}
 
}

這樣訪問這個Controller時會丟擲異常,瀏覽器展示exception.jsp中的內容

以上就簡單的實現了一個捕獲所有異常並跳轉到異常頁面的簡單示例。