springmvcDay02_02
异常处理以及拦截器
-
异常处理
涉及三个点
-
自定义异常类extends Exception
public class SysException extends Exception{ private String exceptionMessage; public String getExceptionMessage() { return exceptionMessage; } public void setExceptionMessage(String exceptionMessage) { this.exceptionMessage = exceptionMessage; } public SysException(String exceptionMessage) { this.exceptionMessage = exceptionMessage; } }
-
自定义异常处理类 implement HandlerExceptionResovler
public class ExceptionResolver implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) { // 1. 首先打印错误信息 e.printStackTrace(); // 2. 判断异常是否为自定义异常的实例 SysException sysException = null; if (e instanceof SysException){ // 如果是自定义异常的实例直接赋值 sysException = (SysException) e; }else { sysException = new SysException("不是自定义异常的实例.."); } // 3. 返回视图解析器 ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("errorMessage",sysException.getExceptionMessage()); modelAndView.setViewName("exceptionResolverView"); return modelAndView; } }
-
springmvc.xml中配置异常处理器
-
-
拦截器
两步:
-
写拦截器 实现HandlerIntercept接口
重写三个方法:
- 执行前 preHandle [访问handler之前]
- 执行后 postHandle [提交handler]
- 执行视图之后 afterCompletion [完成后]
-
在springmvc.xml中配置拦截器
<mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/*"/> <bean class="com.qqhru.interpetor.MyInterceptOne"></bean> </mvc:interceptor> </mvc:interceptors>
-