package com.dream.common;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
/**
* 处理session超时的拦截器
*/
public class SessionTimeoutException implements HandlerInterceptor {
public String[] allowUrls;
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception {
String requestUrl = request.getRequestURI().replace(request.getContextPath(), "");
System.out.println("------------------"+requestUrl+"------------------");
// if(null != allowUrls && allowUrls.length>=1)
// for(String url : allowUrls) {
// if(requestUrl.contains(url)) {
// return true;
// }
// }
//
// User user = (User) request.getSession().getAttribute("user");
// if(user != null) {
// return true; //返回true,则这个方面调用后会接着调用postHandle(), afterCompletion()
// }else{
// // 未登录 跳转到登录页面
// throw new SessionTimeoutException();//返回到配置文件中定义的路径
// }
}
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception {
// TODO Auto-generated method stub
System.out.println("------------------postHandle------------------");
}
@Override
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
// TODO Auto-generated method stub
System.out.println("------------------preHandle------------------");
return false;
}
}
<!-- 拦截器配置 -->
<mvc:interceptors><!-- session超时 -->
<mvc:interceptor>
<mvc:mapping path="/*/*"/>
<bean class="com.dream.common.SessionTimeoutException">
<property name="allowUrls">
<list>
<!-- 如果请求中包含以下路径,则不进行拦截 -->
<value>/login</value>
<value>/js</value>
<value>/css</value>
<value>/image</value>
<value>/images</value>
</list>
</property>
</bean>
</mvc:interceptor>
</mvc:interceptors>
<!-- 自定义异常处理,SimpleMappingExceptionResolver这个类可以是个空类,但是要写,方便在java代码里面使用 -->
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="com.dream.common.SessionTimeoutException">redirect:/login</prop>
</props>
</property>
</bean>