views:

53

answers:

2

I've created two servlets:

UserReceiverServlet receives a username from a form. It then sets the username to an attribute and forwards the request to UserDisplayServlet.

UserDisplayServlet will add the username to a cookie and then display the current continents of both the attribute which was set and the cookie which was stored.

However, while I've managed to determine that the cookie is definitely being created and the value is being stored, when this Servlet goes to look for it, it doesn't find it

Here is UserDisplayServlet. It is correctly receiving a value through request.getAttribute("username"), so attributeUsername isn't the problem...

/**
 * 
 */
package hu.flux.user;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.*;

/**
 * @author Brian Kessler
 *
 */
public class UserDisplayServlet extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public void service (HttpServletRequest request, HttpServletResponse response)
    {
        response.setContentType("text/html");

        String attributeUsername = (String) request.getAttribute("username"); 

        String cookieUsername = null;
    for (Cookie cookie: request.getCookies())
        { if (cookie.getName() == "username") 
            { 
                String value = cookie.getValue();
                if (value.isEmpty()) { value = "--- EMPTY ---"; }
                cookieUsername = cookie.getValue(); 
                break; 
            } 
        }
    if (cookieUsername == null) {cookieUsername = "--- NOT FOUND ---"; }

    String newCookieValue;
    if (!(cookieUsername.isEmpty())) { newCookieValue = cookieUsername;}
    else if (!(attributeUsername.isEmpty())) { newCookieValue = cookieUsername;}
    else { newCookieValue = "UNKOWN";}

        Cookie usernameCookie = new Cookie ("username", attributeUsername);
        usernameCookie.setMaxAge(24*60*60);
        response.addCookie(usernameCookie);

        PrintWriter out = null;
        try { out = response.getWriter(); } 
        catch (IOException e) 
        { 
            System.err.print ("Cannot getWriter():" + e);
            e.printStackTrace();
        }


        out.println("<html>");
        out.println("<head>");
            out.println("<title>User Display Servlet</title>");
        out.println("</head>");
        out.println("<body");

        if ((attributeUsername != null) && (!(attributeUsername.isEmpty())))
        {
            out.println ("<p>I have an attribute which says your username is " 
                    + request.getAttribute("username") + "</p>");
        }
        else { out.println ("<p>The attribute hasn't been set.</p>"); }


        if ((cookieUsername != null) && (!(cookieUsername.isEmpty())))
        {
            out.println ("<p>You have a cookie which says your username is " + cookieUsername + "</p>");
            out.println ("</body></html>");
        }
        else { out.println ("<p>The cookie hasn't been set.</p>"); }


    }


}

If it is helpful, here is the servlet that is receiving the input and forwarding it to the above servlet:

/**
 * 
 */
package hu.flux.user;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.*;

/**
 * This simple servlet receives a username from a form,
 * stores the name in a context attribute,
 * and forwards the context attribute to another servlet
 * which displays the name.
 *  
 * @author Brian Kessler
 *
 */
public class UserReceiverServlet extends HttpServlet 
{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public void service (HttpServletRequest request, HttpServletResponse response)
    {
        String username = request.getParameter("username");
        request.setAttribute("username", username);

        try {

            getServletConfig()
                .getServletContext()
                .getRequestDispatcher("/userdisplay")
                .forward(request, response);
        } catch (ServletException e) {
            System.err.println ("Can't forward: " + e);
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println ("Can't forward: " + e);
            e.printStackTrace();
        }


    }
}

What am I missing to retrieve the value to stored in the cookie?

A: 

How do you know that a cookie has not been set? The HTML body certainly won't tell you because the content is evaluated on the server side not the client side. If you really want the page to tell you if a cookie has been set successfully, you'll need to embed some javascript in the HTML to access the browser's cookie store.

If I was trying to solve this problem, I'd start by looking at the HTTP responses on the server and client side. On the server-side turn on response dumping / logging supported by your webapp container; e.g. for Tomcat, turn on the RequestDumperValve. On the client-side, use the browser's preferences dialogs (or whatever) to look at the contents of the cookie store for the server you are interacting with. Then use the browser's Javascript debugger (or whatever) to see whether the response headers contain headers to set the cookies. (If you are using firefox, install the firebug plugin.)

Stephen C
A cookie seems to be set, but without the value being attached to the name. I can tell because I already have another servlet which, when called, reads my cookies and dumps the contents back to my browser.
Brian Kessler
@Brian - next you need to figure out when it is being set and how, see the suggestions in my answer.
Stephen C
The cookie is being created, just without any value. It is being created by the servlet above. I have used another servlet to confirm this. Moreover, if I change the name of the cookie to something other than "username" (e.g. "test"), there will be a new cookie without any value. Furthermore, Firebug confirms the presence of the cookie without any value.
Brian Kessler
Just played with things a bit more. It looks like the cookie is in fact receiving a value, but UserDisplayServlet doesn't ever find the value (regardless of whether I call it directly or indirectly) and then, if I called that servlet directly it resets the value to nothing.
Brian Kessler
@Brian - well that makes sense. If you look at UserDisplayServlet, you'll see that it puts the **old** value of the cookie into the HTML, then sets the attribute value as the new cookie value.
Stephen C
Yes, but that wasn't the problem. I figured it out. When I searched the cookies for the right one, I was using "==" instead of .equals() ... thus the value I was looking for was never found.
Brian Kessler
+1  A: 

Found the problem:

if (cookie.getName() == "username") 

should have been:

if (name.equals("username")) 

That always trips me up!

Brian Kessler