All the cookies you want

Cookies are designed to make possible conversation on session, but we can use them as we like, to store information on the client.

Here we are about to improve the conversation example so that we could store and retrieve additional information on cookies. To do that we add a private method, cookieTest(), in the Conversation servlet that gets the existing cookies from the request, and put them in the report list, than we'll put them as a session attribute in the request, to pass them to the JSP page where they are shown to the user. Then, we add a new cookie (or replace an old one) to the response array of cookies.

This is the change in the processRequest(), just add a call to cookieTest() before setting the attribute on the session:
// ...
cookieTest(request, response, report);
session.setAttribute("report", report);

Here is the new method:
private void cookieTest(HttpServletRequest request,
        HttpServletResponse response, List report) {
    Cookie[] cookies = request.getCookies();
    if(cookies != null) {
        for(Cookie c : cookies) {
            report.add(c.getName() + ": " + c.getValue());

    // add a new cookie for the next iteration
    long time = System.currentTimeMillis();
    String name = "last" + time % 10;
    String value = "time " + time;
    Cookie cookie = new Cookie(name, value);
    cookie.setMaxAge(5 * 60); // a 5 min life
In the report we'll find not only the lastX (where X is in 0..9) cookies generated by us, but also the JSESSIONID generated by the container.

You could read more on cookies in the sixth chapter of Head First Servlet and JSP, I wrote the first version of this post while I was reading this fun and interesting book.

No comments:

Post a Comment