Section 18.6. Matters of State: Cookies, Hidden Variables, and the Dreaded Back Button


18.6. Matters of State: Cookies, Hidden Variables, and the Dreaded "Back" Button

The toughest part about working with HTML is, perhaps, its statelessness. HTML and browsers were not designed to keep a connection going. It's not a phone call type of connection, where the line is kept open between the browser and the Web server. Rather, it's a one-shot, send-me-what-you've-got mechanism more like postal mail (but without the stamp). Here's the rub: Just because you mail a letter, you can't assume that you'll get an answer back. There is no on-going connection between browser and server, except for the duration of the data transfer. Once you've got your complete page displayed, the connection is gone. [2] About the best one can hope for is that you'll use what, in our postal analogy, would be like a supplied reply envelope. This allows the servlet engine of the Web server to track requests from the same user and provide a session capability across requests. It will use your browsers cookie mechanism to store this session's ID used to track your session. If you don't have sessions on, it will need to use URL rewriting, whereby the URLs generated will have an added parameter, the session ID.

[2] You can go to another page, just be staring at the page for a long long time, or you might have shut down your browser completelyand the server-side servlet will never know.

Unlike the early days in the life of the Web, nowadays virtually everyone has cookies enabled in their browsersanyone who shops at amazon.com, at least. This makes session tracking so much easier for the servlet developer. The Web server handles all that automatically, and you only need to make a few calls to the session-related methods of the HttpRequest.

To get a session for a user, ask for one from the HttpRequest:

 HttpSession session = request.getSession(true); 

The boolean parameter says whether (TRue) or not to create a session if one does not yet exist for this user. Once you have a session, you can store objects associated with that session:

 session.setAttribute("cart", shopCart); 

where shopCart is any serializable Object and "cart" could be any String that you want to use to later identify and retrieve this object, for example:

 Basket myCart = (Basket) session.getAttribute("cart"); 

Notice that we need to explicitly cast the object type returned by getAttribute(), because it returns a generic Object.

18.6.1. Cookies

For any information that you want to save for longer than the duration of a session, you may want to investigate cookieslittle bits of data (4K max; typically only a few bytes) sent to the browser for it to store and send back at a later time. You make a cookie thus:

 Cookie snack = new Cookie("name", "value"); snack.setMaxAge(36000); // lifetime in seconds (10 hours) 

Setting the maximum age of the cookie to a positive value is needed to let the browser know that it needs to store the cookie on disk. After that many seconds the cookie will be discarded by the browser as no longer relevant. Notice, too, that you must send the data inside the cookie as a string, and when you retrieve it, you'll have to parse that string.

Then you can send the cookie as part of a response, along with your other output:

 response.addCookie(snack); 

Getting data back via cookies involves requesting data from the HttpServletRequest object. All the cookies associated with your URL are sent with the HTTP header to this address. You make the call:

 Cookies [] allSuch = request.getCookies(); 

and then you have to look through the list looking for the cookie you want:

 if (allSuch != null) {     for(i=0; i allSuch.length; i++) {         Cookie c1 = allSuch[i];         if ("DesiredCookieName".equals(c1.getName())) {            String result = c1.getValue();            // ... now do something with it         } // endif     } // next cookie } // endif 

While cookies have gotten a lot of press, especially in the early days of Web technology, we've found much less use for them than for session objects. Session objects stay on the server, cannot be modified or deleted by the user, and are easier to look up and use. The drawback, or course, is their limited lifespan. But if you really want to leave data around for the next time some user visits your servlet, you may be better off putting the data in your own database and identifying that user by means of a cookie or by some login mechanism.

Let's take a look at a complete servlet example.



    Java Application Development with Linux
    Java Application Development on Linux
    ISBN: 013143697X
    EAN: 2147483647
    Year: 2004
    Pages: 292

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net