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

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值