【Spring MVC异常处理】——SimpleMappingExceptionHandler

作用

SimpleMappingExceptionHandler对所有异常进行统一处理,将异常类名映射为视图名。

配置方法

在Spring MVC配置文件(我的文件名是dispatcher-servlet.xml)添加如下代码:

<bean id="exceptionResolver" 
	class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
	<property name="exceptionMappings">
		<props>
			<prop key="java.lang.RuntimeException">exception-view-name</prop>
		</props>
	</property>
</bean>

这样,所有的java.lang.RuntimeException异常都会被SimpleMappingExceptionHandler拦截处理,然后跳转到exception-view-name对应的页面。

处理异常的方法

doResolveException(...)

protected ModelAndView doResolveException(HttpServletRequest request, 
		HttpServletResponse response,
		Object handler, Exception ex) {

	// 得到异常所对应的视图的名称
	String viewName = determineViewName(ex, request);
	if (viewName != null) {
		// Apply HTTP status code for error views, if specified.
		// Only apply it if we're processing a top-level request.
		Integer statusCode = determineStatusCode(request, viewName);
		if (statusCode != null) {
			applyStatusCodeIfPossible(request, response, statusCode);
		}
		return getModelAndView(viewName, ex, request);
	}
	else {
		return null;
	}
}

getModelAndView(...)

protected ModelAndView getModelAndView(String viewName, Exception ex) {
	ModelAndView mv = new ModelAndView(viewName);
	//如果没有在配置文件中配置,exceptionAttribute默认值为exception
	if (this.exceptionAttribute != null) {
		if (logger.isDebugEnabled()) {
			logger.debug("Exposing Exception as model attribute '" + 
				this.exceptionAttribute + "'");
		}
		mv.addObject(this.exceptionAttribute, ex);
	}
	return mv;
}

获取异常

在页面获取异常信息${ exception }

猜你喜欢

转载自longying2008.iteye.com/blog/2200856