应用Spring mvc HandlerExceptionResolver 处理异常全局跳转方法
对于系统异常跳转,可以采用全局跳转的方式,避免在每个controller方法做跳转判断,同时打印异常的的请求uri,可以快速查找问题的入口。
1、配置:applicationContext.xml 加入bean <bean class="com.bbc.common.BBCExceptionResolver" />
2、实现 HandlerExceptionResolver 接口,参考如下例子:
public class BBCExceptionResolverimplements HandlerExceptionResolver {
privatestatic Logger logger = Logger.getLogger(BBCExceptionResolver.class);
/**
* 处理异常跳转
*/
@Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
if (ex instanceof org.springframework.web.HttpSessionRequiredException) {
StringuserName = CookieUtil.getUserName(request);
returnnew ModelAndView("user/login").addObject("account",userName);
}
String url = request.getRequestURI();
String param =request.getQueryString();
if (param != null &¶m.length() > 0) {
url += ("?" +param);
}
logger.error("异常跳转: "+ url, ex);//把漏网的异常信息记入日志
return new ModelAndView("error");
}
}