testInterceptor
@RequestMapping(value="testInterceptor") public String testInterceptor( ) { System.out.println("处理请求的方法....!"); return "success"; }
MyInterceptor
package interceptor; 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("拦截请求"); // return true;//true:拦截操作之后,放行 ;false:拦截之后不放行,请求终止; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("拦截响应"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("视图(jsp)被渲染完毕"); } }
MySecondInterceptor
package interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; public class MySecondInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("第二个拦截器,拦截请求...22222"); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("第二个拦截器,拦截响应...22222"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("第二个拦截器,afterCompletion"); } }
springmvc.xml
<!-- 将自己写的拦截器 配置到springmvc中(spring);默认拦截全部请求 --> <mvc:interceptors> <mvc:interceptor> <!-- 指定拦截的路径,基于ant风格 --> <mvc:mapping path="/**"/> <!-- 指定拦不截的路径 --> <mvc:exclude-mapping path="/handler/testUpload"/> <bean class="interceptor.MyInterceptor"></bean> </mvc:interceptor> <mvc:interceptor> <mvc:mapping path="/**"/> <mvc:exclude-mapping path="/handler/testUpload"/> <bean class="interceptor.MySecondInterceptor"></bean> </mvc:interceptor> </mvc:interceptors>
<br/> <a href="handler/testInterceptor">testInterceptor</a> <br/>