How to validate/invalidate sessions jsp/servlets?

前端 未结 2 905
青春惊慌失措
青春惊慌失措 2020-12-05 11:24

I opened the session in my servlet when the user performed a successful login:

HttpSession session = request.getSession(true);
session.setAttribute(\"name\",         


        
相关标签:
2条回答
  • 2020-12-05 12:00

    To Validate the Session

    HttpSession session = request.getSession(true);
    session.setAttribute("name", name);
    

    To invalidate it you need to do

    session.removeAttribute("name");
    session.invalidate();
    

    But you need to keep one thing in mind that the object may became invalid but this doesnot mean that it will cleaned immediately, even after invalidating it after all its attributes gone it is possible that sesssion object will get reused, I got the same user ID and creation time.

    0 讨论(0)
  • 2020-12-05 12:13

    you should call session.getSession(false) - which returns null if there is no current session.

    according to docs

    HttpSession#getSession(boolean create) - create - true to create a new session for this request if necessary; false to return null if there's no current session.

    So the correct way of session value check would -

    HttpSession session = request.getSession(false);
    if(session!=null)
      session.setAttribute("name", name);
    

    and once you invalidate the session -

    HttpSession session = request.getSession(false);
    if(session!=null)
    session.invalidate();
    
    0 讨论(0)
提交回复
热议问题