@ExceptionHandler
在一个controller中定义一个方法,用@ExceptionHandler注解标注。(优先级最高)
@ExceptionHandler
public ModelAndView handlerException(Exception ex) {
Map<String, String> model = new HashMap<String, String>();
model.put("error", ex.toString());
return new ModelAndView("/error/error", model);
}
SimpleMappingExceptionResolver
xml配置
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<!-- 定义异常处理页面用来获取异常信息的变量名,默认名为exception -->
<!--<property name="exceptionAttribute" value="ex"></property>-->
<property name="exceptionMappings">
<props>
<prop key="java.lang.Throwable">error/error</prop>
</props>
</property>
</bean>
这里的exceptionMappings是支持自定义exception的。
自定义异常处理(优先级次之)
继承AbstractHandlerExceptionResolver即可。
public class HandlerError extends AbstractHandlerExceptionResolver {
@Override
protected ModelAndView doResolveException(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2,
Exception arg3) {
ModelAndView mv = new ModelAndView("/error/error");
mv.addObject("error", arg3.getMessage());
return mv;
}
}
xml配置
<bean id="handlerError"
class="com.yvan.error.HandlerError">
</bean>
实际开发程序出现异常错误,上面的几种方式都可以跳转到错误页,但是如果是404的情况,我们需要处理。
- web.xml配置
<error-page>
<error-code>404</error-code>
<location>/WEB-INF/Views/share/404.jsp</location>
</error-page>
这样设置之后要是访问web项目404都会跳转到404.jsp
- 继承DispatcherServlet重写noHandlerFound
public class DefineDispatcherServlet extends DispatcherServlet{
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
protected void noHandlerFound(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
// TODO Auto-generated method stub
arg1.sendRedirect("http://www.csdn.net/");
}
}
这里是重定向了外部网站。
这里说明一下:配置了web.xml中的404,无论…./notFound/404.do或者是…./notFound/404,只要找不到都会跳转到404.jsp,但是利用继承DispatcherServlet重写noHandlerFound,只有访问…./notFound/404.do的时候才会进入noHandlerFound方法。
补充:
在自定义异常处理继承AbstractHandlerExceptionResolver来处理错误的,如果想跳转到外站,如下:
public class HandlerError extends AbstractHandlerExceptionResolver {
@Override
protected ModelAndView doResolveException(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2,
Exception arg3) {
return new ModelAndView(new RedirectView("http://www.csdn.net/"));
}
}