session过期后自动跳转到登陆页

项目需要做一个自动登出的功能,查询了网上的资料,一开始准备用session监听做,按照下面方式配置监听器

1.在项目的web.xml文件中添加如下代码:

<!--添加Session监听器-->
<listener>
<listener-class> 监听器路径 </listener-class>
</listener>

2.编写java类。

public class SessionListener implements HttpSessionListener {
 public void sessionCreated(HttpSessionEvent arg0) {
  // session创建时执行
  SimpleDateFormat simpleFormat = new SimpleDateFormat("mm-ss-ms");
  String nowtimes = simpleFormat.format(new Date());
  User u=null;
  //System.out.println("执行。。 当前时间:"+nowtimes+"_"+u);
  HttpSession ses= arg0.getSession();
  String id=ses.getId()+"_"+ses.getCreationTime();
 }
 public void sessionDestroyed(HttpSessionEvent arg0) {
  // session失效时执行
  SimpleDateFormat simpleFormat = new SimpleDateFormat("mm-ss-ms");
  String nowtimes = simpleFormat.format(new Date()); 
  //System.out.println("session失效了。。 结束时间: "+nowtimes);
 }
}

配置完成后等session失效后成功进入sessionDestroyed方法,准备进行页面跳转操作,突然发现怎么写跳转,愣住了,继续上网请教大神,发现这个监听是做一些后台统计处理的,无法实现页面跳转的功能。

只能放弃这方法了,开始使用过滤器实现

1、web.xml中添加过滤器配置

<filter>
        <filter-name>sessionFilter</filter-name>
        <filter-class>com.orchestrall.web.helper.session.SessionFilter</filter-class>
</filter>
<filter-mapping>
        <filter-name>sessionFilter</filter-name>
        <url-pattern>/actions/*</url-pattern>
</filter-mapping>

2、新建SessionFilter类,实现Filter接口。

public class SessionFilterimplements Filter {
    public void destroy() {
        // TODO Auto-generated method stub
    }
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpSession session = httpRequest.getSession();
        // 登陆url
        String loginUrl = httpRequest.getContextPath() + "/admin/login.jsp";
        String url = httpRequest.getRequestURI();
        String path = url.substring(url.lastIndexOf("/"));
        // 超时处理,ajax请求超时设置超时状态,页面请求超时则返回提示并重定向
        if (path.indexOf(".action") != -1
                && session.getAttribute("LOGIN_SUCCESS") == null) {
            // 判断是否为ajax请求
            if (httpRequest.getHeader("x-requested-with") != null
                    && httpRequest.getHeader("x-requested-with")
                            .equalsIgnoreCase("XMLHttpRequest")) {
                httpResponse.addHeader("sessionstatus", "timeOut");
                httpResponse.addHeader("loginPath", loginUrl);
                chain.doFilter(request, response);// 不可少,否则请求会出错
            } else {
                String str = "<script language=‘javascript‘>alert(‘会话过期,请重新登录‘);"
                        + "window.top.location.href=‘"
                        + loginUrl
                        + "‘;</script>";
                response.setContentType("text/html;charset=UTF-8");// 解决中文乱码
                try {
                    PrintWriter writer = response.getWriter();
                    writer.write(str);
                    writer.flush();
                    writer.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            chain.doFilter(request, response);
        }
    }
    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub
    }
}

3、客户端JS,用于ajax请求session超时

对于jquery

<script type="text/javascript">
$(document).ajaxComplete(function(event, xhr, settings) {  
    if(xhr.getResponseHeader("sessionstatus")=="timeOut"){  
        if(xhr.getResponseHeader("loginPath")){
            alert("会话过期,请重新登陆!");
            window.location.replace(xhr.getResponseHeader("loginPath"));  
        }else{  
            alert("请求超时请重新登陆 !");  
        }  
    }  
});  
</script>

对于extjs的ajax请求

Ext.Ajax.on(‘requestcomplete‘,checkUserSessionStatus, this);
    function checkUserSessionStatus(conn,response,options){
        if(response.getResponseHeader("sessionstatus") == ‘timeout‘){
            if(response.getResponseHeader("loginPath")){
                alert("会话过期,请重新登陆!");
                window.top.location.href = response.getResponseHeader("loginPath");
            }else{
                alert("请求超时请重新登陆 !");
            }
        }
    }

如果使某个ajax请求不受全局方法的影响,那么可以在使用$.ajax()方法时,将参数中的global设置为false,jquery代码如下:

$.ajax({
    url:"test.html",
    global:false//不触发全局ajax事件
})

session过期后自动跳转到登陆页

时间: 2024-08-04 23:40:31

session过期后自动跳转到登陆页的相关文章

当session过期后自动跳转到登陆页而且会跳出iframe框架

写项目时在重定向后一直存在一个问题就是重定向后登陆页面会出现在跳出的子框架里. 解决方法: 在登陆界面的<body></body>里加上 1 <script type="text/javascript"> 2 //session过期后刷新父页面 3 if (window != top) 4 top.location.href = location.href; 5 </script> 即可跳出iframe框架

计时3秒后自动跳转到登录页

<script> //计时3秒后自动跳转到登录页 var i = 3; var time_out; time_out = setInterval("time()", 800); function time() { if(i == 0){ window.location.href = "/user/login"; clearInterval(time_out); } document.getElementById("time").inn

MVC 访问IFrame页面Session过期后跳转到登录页面

Web端开发时,用户登录后往往会通过Session来保存用户信息,Session存放在服务器,当用户长时间不操作的时候,我们会希望服务器保存的Session过期,这个时候,因为Session中的用户信息取不到了,就需要用户重新登录,重新保存Session. Asp.net MVC提供了过滤器,让我们可以很方便的控制访问Action时要处理的事情,针对Session过期后页面跳转,我们可以封装一下Controller的OnActionExecuting方法作为基Controller,如下: pub

关于使用struts2时子窗体页面跳转后在父窗体打开的问题以及Session过期后的页面跳转问题

问题1:传统的系统界面,iframe了三个页面,上,左,右,用户点击注销的按钮在上面得top.jsp里面,方法:<a href="../adminAction/admin_logout.action">退出系统</a>退出之后你会发现,只是刷新了top.jsp上面那个iframe,其他两个还在,如何解决? 解决办法: target="_top",就就是它.加多这个变成:<a href="../adminAction/admin

使用幕布时,在Session过期后,弹出框加载出登陆的HTML的问题

思路:在登陆页面判断当前加载的Url是否时login/index ,如果不是跳转到登陆页 //设置或获取对象指定的文件名或路径. var Url = window.location.pathname; //当前Url为localhost为 ‘/’ //toLowerCase()将Url转化成小写进行比较 if (Url != "/" && Url.toLowerCase() != "/login/index") { window.location.h

js实现网页多少秒后自动跳转到指定网址

在网上搜了一下,关于这个技术处理有多种方法,我只记下我在视频里学到的三种: 1.用一个response.sendRedirect("目标页面.jsp\.htm");实现直接跳转: 2.有时我们需要有点提示,比如“x秒后自动跳转,若没有跳转,请点击此处”,则可以在myeclipse中调用Snippets中的Delay Go To URL.会自动生成如下代码: 代码如下: <script language="JavaScript1.2" type="te

用js在网页上完成倒计时3秒后自动跳转到另一个页面

<body> <div id="time"></div> <a href="#" onclick="stop()">停止</a> <script type="text/javascript"> var i=3; function changeTime(){ document.getElementById("time").innerHTM

解决session过期后登录页面嵌套在框架中的问题

只要在登录页面中加入一下脚本即可: <script language="text/javascript"> //在嵌套时,就刷新上级窗口 if(window.parent!=window){ window.parent.location.reload(true); } </script> 解决session过期后登录页面嵌套在框架中的问题,布布扣,bubuko.com

jBox如何实现3秒后自动跳转

首先要调用window的定时器,里面有一个函数,如下: $.jBox.tip("注册成功,3秒后自动跳转--", 'success'); window.setTimeout(function () { window.location.href = document.getElementById('strBackUrl').value }, 3000);