SpringMVC拦截器实现监听session是否过期详解

2025-05-27 0 66

本文主要向大家介绍了SpringMVC拦截器实现:当用户访问网站资源时,监听session是否过期的代码,具体如下:

一、拦截器配置

?

1

2

3

4

5

6

7

8

9

10

11

12
<mvc:interceptors>

<mvc:interceptor>

<mvc:mapping path="/**"/>

<mvc:exclude-mapping path="/user/login"/> <!-- 不拦截登录请求 -->

<mvc:exclude-mapping path="/user/logout"/> <!-- 不拦截注销请求 -->

<mvc:exclude-mapping path="*.jsp"/>

<mvc:exclude-mapping path="*.html"/>

<mvc:exclude-mapping path="*.js"/>

<mvc:exclude-mapping path="*.css"/>

<bean class="org.huaxin.interceptor.AccessInterceptor"></bean>

</mvc:interceptor>

</mvc:interceptors>

二、拦截器编码

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,

Object obj) throws Exception {

System.out.println("[AccessInterceptor]:preHandle执行");

HttpSession session = request.getSession();

ServletContext application = session.getServletContext();

if(application.getAttribute(session.getId()) == null){ //未登录

PrintWriter out = response.getWriter();

StringBuffer sb = new StringBuffer("<script type=\\"text/javascript\\" charset=\\"UTF-8\\">");

sb.append("alert(\\"你的账号被挤掉,或者没有登录,或者页面已经过期,请重新登录\\")");

sb.append("window.location.href='/user/logout';");

sb.append("</script>");

out.print(sb.toString());

out.close();

return false;

}else{ //已经登录

return true;

}

}

三、总结

1.注意这里使用的拦截器是HandlerInterceptor,你的拦截器需要实现这个接口

2.在你的登录handler里面,要将session保存到application中,方便根据sessionId来判断是否存在session

3.sb.append("window.location.href='/user/logout';"); 这行代码是说,执行注销操作,在你的/user/logout 这个handler里面得把页面解析到登录页,方便重新登录

以上就是本文关于SpringMVC拦截器实现监听session是否过期详解的全部内容,希望对大家有所帮助,如有不足之处,欢迎留言指出。小编会及时进行更改,感谢朋友们对本站的支持!

原文链接:http://www.cnblogs.com/javafucker/p/7726202.html

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 SpringMVC拦截器实现监听session是否过期详解 https://www.kuaiidc.com/77608.html

相关文章

发表评论
暂无评论