在applicationContext.xml 中配置如下:(此配置拦截 /dynamic/dynamic.do中 action 以 checklogin 字符串结尾的请求)
<mvc:interceptors>
<mvc:interceptor>
<!--设置拦截的路径 mvc:mapping指定到哪个action , 用mappingURL匹配方法-->
<mvc:mapping path="/dynamic/dynamic.do" />
<bean class="com.weshare.common.web.LoginInterceptorController">
<property name="mappingURL" value="^.*checklogin$" />
</bean>
</mvc:interceptor>
</mvc:interceptors>
拦截器类: 说明都在注释里面
public class LoginInterceptorController extends HandlerInterceptorAdapter {
public LoginInterceptorController() {
// TODO Auto-generated constructor stub
}
private String mappingURL;// 利用正则映射到需要拦截的路径
public void setMappingURL(String mappingURL) {
this.mappingURL = mappingURL;
}
/**
* 在Controller方法前进行拦截
*/
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
/* 在aC-context.xml中匹配的 /dynamic/dynamic.do, 在这里匹配action 拦截对应的方法
String url = request.getRequestURL().toString(); /dynamic/dynamic.do
request.getParameter("action"); addDynamic
*/
String url = request.getParameter("action");
if (mappingURL == null || url.matches(mappingURL)) {
System.out.println("匹配成功、");
//TODO
return true;
}
System.out.println("preHandle()");
return true;
}
/**
* This implementation is empty.
*/
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
System.out.println("postHandle()");
}
/**
* 在Controller方法后进行拦截
*/
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
System.out.println("afterCompletion()");
}
}