在springmvc.xml文件中配置:
<mvc:interceptors>
<!-- 配置自定义的拦截器 -->
<bean class="com.gong.springmvc.interceptors.FirstInterceptor"></bean>
<mvc:interceptor>
<mvc:mapping path="/emps"/>
<bean class="com.gong.springmvc.interceptors.SecondInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
FirstInterceptor.java
package com.gong.springmvc.interceptors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class FirstInterceptor implements HandlerInterceptor{
//该方法在目标方法之前被调用
//如果返回true,则继续调用后续的拦截器和目标方法,若为false,则不会在调用后续的拦截器和目标方法
//该方法可以考虑做权限、日志、事务等
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
System.out.println("[FirstInterceptor] preHandle");
return true;
}
//调用目标方法之后,但在渲染视图之前被调用
//可以修改请求域中的属性或视图做出修改
@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
System.out.println("[FirstInterceptor] postHandle");
}
//在渲染视图之后被调用
//释放资源
@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
System.out.println("[FirstInterceptor] afterCompletion");
}
}
SecondInceptor.java
package com.gong.springmvc.interceptors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class SecondInterceptor implements HandlerInterceptor{
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
System.out.println("[SecondInterceptor] preHandle");
return true;
}
@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
System.out.println("[SecondInterceptor] postHandle");
}
@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
System.out.println("[SecondInterceptor] afterCompletion");
}
}
在<mvc:mapping path="/emps"/>中可以配置拦截的url地址。
在<mvc:exclude-mapping path=""/>中可以配置不拦截的url地址。
像这种定义在<mvc:interceptors>下的<bean class="com.gong.springmvc.interceptors.FirstInterceptor"></bean>,没有指定是否拦截,则默认所有请求都调用该拦截器。
在<mvc:interceptor>下使用<mvc:mapping path="/emps"/>表明要拦截该地址,调用的拦截器是SecondInterceptor。
比如说,我们如果请求地址是/emps,那么两个拦截器都会被调用,在控制台可以看到:
如果请求地址不是/emps,那么只会调用FirstInterceptor拦截器: