SpringMVC拦截器
拦截器(interceptor)的作用
- SpringMVC的拦截器类似于Servlet开发中的过滤器Filter,用于对处理器进行预处理和后处理。
- 将拦截器按一定的顺序联结成一条链,这条链称为拦截器链(interceptor Chain)。在访问被拦截的方法或字段,拦截器链中的拦截器就会按其之前定义的顺序被调用。拦截器也是AOP思想的具体体现。
拦截器快速入门
- 创建拦截器类实现HandlerInterceptor接口
public class MyInterceptor1 implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
System.out.println("preHandle.....");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
System.out.println("postHandle.....");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { System.out.println("afterCompletion....");
}
}
- 配置拦截器 spring-mvc.xml
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<mvc:exclude-mapping path="/user/login"/>
<bean class="com.zyh.interceptor.MyInterceptor1"></bean>
</mvc:interceptor>
</mvc:interceptors>
- 测试拦截器的拦截效果
SpringMvc异常处理
异常处理两种方式
- 使用SpringMVC提供的简单异常处理器SimpleMappingExceptionResolver
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="defaultErrorView" value="error"/>
<property name="exceptionMappings">
<map>
<entry key="com.zyh.exception.MyException" value="error"/>
<entry key="java.lang.ClassCastException" value="error"/>
</map>
</property>
</bean>
- 使用Spring的异常处理接口HandlerExceptionResolver自定义自己的异常处理器
- 创建异常处理器类实现HandlerExceptionResolver
public class SysExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
SysException ex = null;
if (e instanceof SysException){
ex = (SysException)e;
}else {
e = new SysException("系统正维护。。。");
}
ModelAndView mv = new ModelAndView();
mv.addObject("errorMsg",ex.getMessage());
mv.setViewName("error");
return mv;
}
}
<bean id="sysExceptionResolver" class="com.exception.SysExceptionResolver">
</bean>
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/testException")
public String testException() throws SysException {
System.out.println("testException执行了");
try {
int a = 10/0;
} catch (Exception e) {
e.printStackTrace();
throw new SysException("查询所有用户出错率");
}
return "success";
}