2

Hi Can anyone plz let me know what would be the problem in the following code.In this below code I have invalidated my session after creating the new session by using the http session.getsession(true) and setting the attribute also.Once I click the logout i am invalidating the session but that is not became null.

Here I am not getting null System.out.println("sess"+sess)

HttpSession sess = request.getSession(false);
sess.removeAttribute("name");
sess.invalidate(); 
System.out.println("sess"+sess);
Leos Literak
  • 8,805
  • 19
  • 81
  • 156
user3214269
  • 219
  • 2
  • 8
  • 23

2 Answers2

1

Invalidating session means that server forgets it so once you call getSession() again, you will receive new session. Existing variable (sess) is not affected, it is just not stored internally in servlet container. So there is no reason your variable to be set to null in your code.

    HttpSession session = request.getSession();
    Date date = (Date) session.getAttribute("TEST");
    System.out.println("date = " + date);
    if (date == null) {
        session.setAttribute("TEST", new Date());
    }
    if (new Random(System.currentTimeMillis()).nextInt(10) > 7) {
        session.invalidate();
    }

Put this code into servlet and watch container logs. It shall recreate session in 30 percent., otherwise it will print stored key.

Leos Literak
  • 8,805
  • 19
  • 81
  • 156
  • Then how to check my session has invalidate or not? Could u plz elaborate your answer. – user3214269 Feb 28 '14 at 05:23
  • How come is possible to became new session.there I am not creating any session. – user3214269 Feb 28 '14 at 05:25
  • For example insert new key holding current date in session. When you get session, try to look it up and print it, otherwise set it. Then invalidate session and reload. Hmm, I rather post some code – Leos Literak Feb 28 '14 at 05:28
  • @user3214269 request.getSession(false); will not return any new session instead it will return a session which was created before or null if no session was created before. – Yahya Arshad Feb 28 '14 at 05:34
  • Just i want check My session is invalidated or not . If the session gets invalidated or null,I will kick back my user to login page that's it I wanted to happen in my program. – user3214269 Feb 28 '14 at 06:06
  • Use my code as sample. SImply test, if User object is set or not. If it is not, then redirect to login. Your logout servlet will call session.invalidate(). – Leos Literak Feb 28 '14 at 06:12
1

As API said,

Invalidates this session then unbinds any objects bound to it.

It doesn't need to be null, it just unbinds the objects. You can check whether your previously set attributes are still there in the session.

Abimaran Kugathasan
  • 31,165
  • 11
  • 75
  • 105