spring攔截器配置
在spring.xml中加入
<!-- 配置攔截器 -->
<mvc:interceptors>
<mvc:interceptor>
<!-- 匹配的是url路徑, 如果不配置或/**,將攔截所有的Controller -->
<mvc:mapping path="/**" />
<bean class="cn.yld.webchatapp.service.InterceptorService">
<property name="excludedUrls">
<list>
<value>/test1</value>
</list>
</property>
</bean>
</mvc:interceptor>
<!-- 當設定多個攔截器時,先按順序呼叫preHandle方法,然後逆序呼叫每個攔截器的postHandle和afterCompletion方法 -->
</mvc:interceptors>
excludedUrls是可以訪問的資源路徑
InterceptorService.java檔案內容
package cn.yld.webchatapp.service;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
public class InterceptorService extends HandlerInterceptorAdapter {
private List<String> excludedUrls;
public void setExcludedUrls(List<String> excludedUrls) {
this.excludedUrls = excludedUrls;
}
/**
* 該攔截器將對請求報文中的mobile進行校驗,不在資料庫中的將不允許訪問本系統資源 返回true訪問資源,訪問false不能訪問資源
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
// TODO Auto-generated method stub
System.out.println("我是preHandle");
String requestUri = request.getRequestURI();
for (String url : excludedUrls) {
if (requestUri.endsWith(url)) {
return true;
}
}
String requesturl = request.getContextPath();
System.out.println("requesturl:"+requesturl);
response.sendRedirect(requesturl + "/tradeapi/test1");
return false;
}
@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");
}
}