springmvc中拦截器使用
1.contorller中:
@RequestMapping("/testinterceptor")public String testinterceptor(HttpServletRequest request){
System.out.println("执行了controller中的testinterceptor方法");
return "success";
}
2.在interceptor包中创建MyInterceptor类实现接口HandlerInterceptor
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.ui.ModelMap;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.context.request.WebRequestInterceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class MyInterceptor implements HandlerInterceptor {
@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
// TODO Auto-generated method stub
System.out.println("afterCompletion");
}
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
// TODO Auto-generated method stub
System.out.println("postHandle");
}
@Override
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
// TODO Auto-generated method stub
System.out.println("preHandle");
return true;
}
}
//打印顺序:preHandle-->执行了controller中的testinterceptor方法-->postHandle-->afterCompletion
<mvc:interceptors>
<!-- 过滤所有的请求 -->
<!-- <bean class="com.springmvc.interceptor.MyInterceptor"/> -->
<!-- 过滤特定路径的请求,路径要从根路径开始设置-->
<mvc:interceptor>
<mvc:mapping path="/test1controller/testinterceptor.do"/>
<bean class="com.springmvc.interceptor.MyInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>