自定義攔截器類
public class SessionInterceptor extends HandlerInterceptorAdapter {css
public SessionInterceptor() { // TODO Auto-generated constructor stub } private List<String> excludedUrls; //經過屬性註冊不須要過濾的url list public void setExcludedUrls(List<String> excludedUrls) { this.excludedUrls = excludedUrls; } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String requestUrl = request.getRequestURI(); //排除不須要過濾的URL for(String url:excludedUrls) { if(requestUrl.endsWith(url)) { return true; } } //獲取當前的會話session HttpSession session = request.getSession(); if(session.getAttribute("userid") == null) { //若登陸session過時或不存在就跳轉到login頁面 request.getRequestDispatcher("/login.jsp").forward(request, response); return false; } return true; }
}
springmvc-servlet.xml 攔截器註冊web
<mvc:interceptors>
<mvc:interceptor>
<!--
/*的意思是全部文件夾及裏面的子文件夾
/是全部文件夾,不含子文件夾
/是web項目的根目錄
-->
<mvc:mapping path="/**" />
<!-- 需排除攔截的地址 -->
<!-- <mvc:exclude-mapping path="/login"/> -->
<bean id="commonInterceptor" class="com.skcc.chart.interceptor.SessionInterceptor">
<property name="excludedUrls">
<list>
<value>/login</value>
</list>
</property>spring
</bean> <!--這個類就是咱們自定義的Interceptor --> </mvc:interceptor> <!-- 當設置多個攔截器時,先按順序調用preHandle方法,而後逆序調用每一個攔截器的postHandle和afterCompletion方法 --> </mvc:interceptors> <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory --> <mvc:resources mapping="/resources/**" location="/resources/" order="0" /> <mvc:resources mapping="/js/**" location="/js/" order="0" /> <mvc:resources mapping="/css/**" location="/css/" order="0" /> <!-- Spring MVC不處理靜態資源 --> <mvc:default-servlet-handler /> <!-- 配置註解的處理器映射器和處理器適配器 --> <mvc:annotation-driven ></mvc:annotation-driven> HandlerInterceptorAdapter不能攔截WEB-INF目錄之外的jsp文件;若需攔截默認index.jsp;能夠將index.jsp移動目錄到WEB-INF下便可;