Saturday, January 16, 2016

HttpSession


Session operation principle
Each session object has an id, using "JSESSIONID" in cookie to pass session id between client and server.
This cookie will be destroyed immediately when browser closed.
To still keep this session after browser closed, we need to overwrite the "JSESSIONID" cookie with the new one(in tomcat, the "JSESSIONID" string must be all uppercase):  
 HttpSession session = request.getSession();
 session.setAttribute("data", data);
 Cookie cookie = new Cookie("JSESSIONID",session.getId());
 cookie.setMaxAge(60*30); //session timeout in 30 minutes
 response.addCookie(cookie);

Request with session id


Set Session
 HttpSession session = request.getSession();//get session, if no session, create a new one
 //HttpSession session = request.getSession(true); //same as no parameter
 //HttpSession session = request.getSession(false); //if no session, return null
 session.setAttribute(String, Object);
 session.setMaxInactiveInterval(30); // precise in seconds
Get Session
 request.getSession();
 session.getAttribute(String); //return null if not exists
 
Delete object from Session
 session.removeAttribute(String);
Unbind Session
 request.getSession();
 session.invalidate(); //destroy the session, unbind all objects in session
                       //Normally used when safe sign out
  • Session stays in memory
  • One Session only work with one client browser(some wired browsers using same core may share the same session)
  • Session default life time: 30 minutes, default for site can be changed in tomcat/conf/web.xml, default for app can be changed in web.xml
    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>
    
  • The precise in xml configs is in minutes, setMaxInactiveInterval(30) is in seconds
  • If another request proceed within the timeout, the session clock will be reset
  • If webapp reload/restart, all session will be destroyed


No comments:

Post a Comment