session过期跳转登录页面_html/css_WEB-ITnose

WBOY
풀어 주다: 2016-06-24 11:52:07
원래의
1425명이 탐색했습니다.

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

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

?

1

2

3

4

 监听器路径 

2.编写java类。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

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中添加过滤器配置

?

1

2

3

4

5

6

7

8

        sessionFilter

        com.orchestrall.web.helper.session.SessionFilter

        sessionFilter

        /actions/*

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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

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>alert('会话过期,请重新登录');" </script>

                        + "window.top.location.href='"

                        + loginUrl

                        + "';";

                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

?

1

2

3

4

5

6

7

8

9

10

11

12

<script> </script>

$(document).ajaxComplete(function(event, xhr, settings) {  

    if(xhr.getResponseHeader("sessionstatus")=="timeOut"){  

        if(xhr.getResponseHeader("loginPath")){

            alert("会话过期,请重新登陆!");

            window.location.replace(xhr.getResponseHeader("loginPath"));  

        }else{  

            alert("请求超时请重新登陆 !");  

        }  

    }  

});  

对于extjs的ajax请求

?

1

2

3

4

5

6

7

8

9

10

11

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代码如下:

?

1

2

3

4

$.ajax({

    url:"test.html",

    global:false//不触发全局ajax事件})

원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!