CS 318 - Week 9 Lecture - 3-29-13

*   true fact: HTTP, by itself, is STATELESS

    in "plain" HTTP, there is no way to associate
    a request with a previous request

*   there are various add-ons and kluges to
    allow information from a previous request --
    state information, if you will -- to
    be associated with a request;

    in Java, Java creates an HttpSession object
    for each "logical" browser session;

    we can add attributes to this session object,
    we can retrieve attributes from this
    session object,
    we can invalidate this session when we're done

*   basic Java syntax for this:

    HttpServletRequest object has a method
    getSession, one of whose versions accepts
    a boolean argument:

    getSession returns the current HttpSession
    associated with the calling request,
    OR if there is no current session and
    the argument is true, return a new session

    HttpSession session = request.getSession(true);

    *   NOTE!!!!!!
        since this might modify the response
	header (if cookies are the session
	tracking mechanism), this needs to
	be called BEFORE you retrieve a
	PrintWriter or a ServletOutputStream	
	for the response!!!

*   your session object has many useful methods. 
    Here are a few:

    void setAttribute(String name, Object value)

    *   this binds an Object value with this
        name in this session

    Object getAttribute(String name)

    *   this returns the Object currently bound
        to the given name in this session 

        returns null if NO object is bound
	under this name

    Boolean isNew()
    
    *   returns true if the client does not
        yet know about this session
	OR if the client chooses not to join
	the session

    void invalidate()

    *   invalidates the calling session and
        unbinds any objects bound to it

    *   CLASS CODING STD - your code SHOULD
        call invalidate when the session
	is logically complete!

    *   closing the browser does NOT destroy
        the session!
	...although it CAN expire after some
	amount of time,
	...and if the server is restarted,
	it would also be destroyed

    String getId()
     
    *   returns a String containing the unique
        identifier assigned to the calling
	session

*   fragment-examples:

    in 1 servlet:

    HttpSession session = request.getSession(true);
    String whatsYourName = "Ann";
    session.setAttribute("username", whatsYourName);

    in another servlet:

    HttpSession session = request.getSession(true);
    ...
    out.println("Welcome, " +
        (String) session.getAttribute("username")
        + "!");