拦截器也算得上是spring中的一大特色,即使没用过spring的拦截器至少也用过struts2的拦截器,拦截器大多数情况都是用来做权限的控制的,极少情况下用来初始化资源或释放资源。springmvc当然也可以直接使用拦截器,而且使用起来也特别简单。
一 springmvc的拦截器实现方式
springmvc实现拦截器主要有以下2种方式:
1 实现HandlerInterceptor接口
package com.sxt.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 { public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("最后执行!!!一般用于释放资源!"); } public void postHandle(HttpServletRequest request,HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("Action执行之后,生成视图之前执行!"); } public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception { System.out.println("action之前执行!!"); return true; } }
package com.sxt.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import 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 true; } }
二 springmvc拦截器的配置
<mvc:interceptors> <bean class="com.sxt.interceptor.MyInterceptor"></bean> <!-- 拦截所有springmvc的url! --> <mvc:interceptor> <mvc:mapping path="/user.do" /> <!--<mvc:mapping path="/test/*" />--> <bean class="com.sxt.interceptor.MyInterceptor2"></bean> </mvc:interceptor> </mvc:interceptors>
原文地址:http://blog.csdn.net/walkcode/article/details/41966803