13.07.2015 Views

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

18.6 Matters of State: Cookies, Hidden Variables, and the Dreaded “Back” Butt<strong>on</strong>415Cookie snack = new Cookie("name", "value");snack.setMaxAge(36000); // lifetime in sec<strong>on</strong>ds (10 hours)Setting the maximum age of the cookie to a positive value is needed to letthe browser know that it needs to store the cookie <strong>on</strong> disk. After that manysec<strong>on</strong>ds the cookie will be discarded by the browser as no l<strong>on</strong>ger relevant. Notice,too, that you must send the data inside the cookie as a string, and whenyou retrieve it, you’ll have to parse that string.Then you can send the cookie as part of a resp<strong>on</strong>se, al<strong>on</strong>g with yourother output:resp<strong>on</strong>se.addCookie(snack);Getting data back via cookies involves requesting data from theHttpServletRequest object. All the cookies associated with your URL aresent 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} // endifWhile cookies have gotten a lot of press, especially in the early days of Webtechnology, we’ve found much less use for them than for sessi<strong>on</strong> objects. Sessi<strong>on</strong>objects stay <strong>on</strong> the server, cannot be modified or deleted by the user, and areeasier 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 visitsyour servlet, you may be better off putting the data in your own database andidentifying that user by means of a cookie or by some login mechanism.Let’s take a look at a complete servlet example.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!