springMVC源码分析--异常处理机制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中的内容


以上就简单的实现了一个捕获所有异常并跳转到异常页面的简单示例。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值