Spring MVC中的拦截器(Interceptor)类似于Servlet中的过滤器(Filter),它主要用于拦截用户请求并作相应的处理。例如通过拦截器可以进行权限验证、记录请求信息的日志、判断用户是否登录等。
使用拦截器的步骤如下:
第一步:添加一个拦截器的类 实现HandlerInterceptor接口
package org.cjr.interceptor.copy;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
System.out.println("拦截请求");
// true 代表拦截后 放行 , false 代表请求终止
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
System.out.println("拦截响应");
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
System.out.println("渲染完成");
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}
第二步:xml 配置拦截器
<!-- 配置拦截器 -->
<mvc:interceptors >
<mvc:interceptor>
<!--拦截路径 -->
<mvc:mapping path=""/>
<!--不拦截路径 -->
<mvc:exclude-mapping path=""/>
<bean class="org.cjr.interceptor.copy.MyInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
测试结果: