1.简介
过滤器是Servlet概念 拦截器是SpringMVC概念(准确说是MVC框架概念)
2.CustomInterceptor
public class CustomInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 请求分发前 controller前
System.out.println("CustomInterceptor preHandle");
// false表示不往下执行
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// controller执行后 View渲染前
System.out.println("CustomInterceptor postHandle");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// View渲染后
System.out.println("CustomInterceptor afterCompletion");
}
}
3.总结
过滤器主要是函数回调实现 而拦截器是通过反射及动态代理实现。过滤器可以拦截更多的请求 拦截器更加灵活