1. 程式人生 > >Spring mvc Interceptor 解決Session超時跳轉

Spring mvc Interceptor 解決Session超時跳轉

Spring mvc Interceptor 解決Session超時

1:在spring_xxx.xml里加入相關配置

	<mvc:interceptors>
		<mvc:interceptor>
			<mvc:mapping path="/*/*" />
			<bean class="com.teachmanage.mvc.interceptor.SessionTimeoutInterceptor" >
				<property name="allowUrls">
			        <list>
			          <value>/login</value>
			          <value>/login/logout</value>
			        </list>
		     	</property>
		    </bean>
		</mvc:interceptor>
	</mvc:interceptors>
	
	<!-- exception handler -->
	<bean id="handlerExceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver" >
		<property name="exceptionMappings">
			<props>
				<prop key="com.teachmanage.mvc.exception.SessionTimeoutException">redirect:/login</prop>
			</props>
		</property>
	</bean>

上述配置裡,list中的url為允許訪問的url,即從這些url訪問的話,不需要判斷session是否超時。(為什麼這些url能夠不判斷,是在下述攔截器程式碼裡實現的。)

攔截生效後,會丟擲SessionTimeoutException,跳轉到/login。這裡的redirect:/login是指controller裡對應的url,如果想跳轉到login.jsp,則直接/login。

2:建立SessionTimeoutInterceptor

public class SessionTimeoutInterceptor implements HandlerInterceptor   {

	private List<String> allowUrls = new ArrayList<String>();
	public List<String> getAllowUrls() {
		return allowUrls;
	}
	public void setAllowUrls(List<String> allowUrls) {
		this.allowUrls = allowUrls;
	}

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, 
			Object handler) throws Exception {
		String requestUrl = request.getRequestURI();
		for(String url : allowUrls) {
			if(requestUrl.endsWith(url)) {
				return true;
			}
		}
		String session = TypeConvertCommon.toString(WebUtils.getSessionAttribute(request, "User_id"));
		if("".equals(session)) {
			throw new SessionTimeoutException();
		} else {
			return true;
		}
	}
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, 
			Object handler, ModelAndView modelAndView) throws Exception {
		
	}
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, 
			Object handler, Exception ex) throws Exception {
		
	}
}

該攔截器需要實現HandlerInterceptor介面,否則會報錯No matching editors or conversion strategy found。不過postHandle和afterComletion暫時無事可做,空著就可以了。

還需要建立一個SessionTimeoutException類,不過不需要寫入程式碼,空著就行。

3:如果專案使用了iframe,則超時跳轉時會造成登陸頁面內嵌到當前頁面,可以在登陸畫面上加上如下js程式碼:

		if (window != top) {
			top.location.href = location.href;
		}