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;
}