Spring MVC 的拦截器类似于Servlet 开发中的过滤器Filter,用于对Controller进行预处理和后处理。
功能:定义处理逻辑,拦截到之后如何处理
拦截器方法的执行时机:
1):preHandle:控制器方法执行之前执行,返回结果为true表示放行,如果返回为false,表示拦截(可以做权限拦截,登录检查拦截).
2):postHandle:控制器方法执行后,视图渲染之前执行(可以加入统一的响应信息).
3):afterCompletion:视图渲染之后执行(处理Controller异常信息,记录操作日志,清理资源等)
实现接口 org.springframework.web.servlet.HandlerInterceptor
public class MyInterceptor implements HandlerInterceptor{
@Override
//前置拦截(一般情况下只配置前置拦截即可)
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
Object user = session.getAttribute("usersession");
if(user == null) {
response.sendRedirect("/login.html");
return false;
}
return true;
}
@Override
//后置拦截
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("MyInterceptor.postHandle..");
}
@Override
//最终拦截(视图渲染之后)
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("MyInterceptor.afterCompletion..");
}
}
org.springframework.web.servlet.handler.HandlerInterceptorAdapter
public class MyInterceptor2 extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("MyInterceptor2.preHandle");
return super.preHandle(request, response, handler);
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("MyInterceptor2.postHandle");
super.postHandle(request, response, handler, modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("MyInterceptor2.afterCompletion");
super.afterCompletion(request, response, handler, ex);
}
}
功能:用于配置拦截哪些资源
1.定义拦截器有两种方式,可以实现HandlerInterceptor接口,也可以实现HandlerInterceptorAdapter类.
2.拦截器只能在访问controller 的方法时进行拦截(只能拦截请求).
3.拦截器可以在访问controller的方法前,访问controller方法之后,和视图渲染完成之后三个时机进行功能的增强.
4./和/**的区别
/:只能匹配一级路径
/**:匹配多级路径