#1
  1. PHP & Java Error Master
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Jun 2003
    Location
    My Computer
    Posts
    1,219
    Rep Power
    0

    Trouble getting cookies


    when i try to search for a cookie, I get a NullPointerExeception error. The code is straight off of devshed, so I'm thoroughly confused as to why it's not working.
    Code:
    // The name of the cookie being stored on the client.
    Cookie cookieUid = null;
    
    // If it doesn't exist, use this as the NAME part of NAME=VALUE
    String cookieName = "user_id3";
    int cookieFound = 0;
    int sessionFound = 0;
    
    // This will store the value of the cookie
    String tempString;
    int count = 0; // just a counter
    
    
    // Request all the client cookies
    Cookie[] cookies = request.getCookies();
    
    // Go through the array looking for our cookie
    for(int i = 0; i < cookies.length; i++)
    {
    	cookieUid = cookies[i];
    	if (cookieName.equals(cookieUid.getName()))
    	{
    		cookieFound = 1;
    		break;
    	}
    }
  2. #2
  3. No Profile Picture
    Moderator =(8^(|)
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Feb 2002
    Location
    Sacramento, CA
    Posts
    1,710
    Rep Power
    14
    You did send the cookie to the client in a previous response, right?
    -james
  4. #3
  5. PHP & Java Error Master
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Jun 2003
    Location
    My Computer
    Posts
    1,219
    Rep Power
    0
    Well, no.
    The point of checking for the cookie is to see if it is there.
  6. #4
  7. No Profile Picture
    Clueless llama
    Devshed Regular (2000 - 2499 posts)

    Join Date
    Feb 2001
    Location
    Lincoln, NE. USA
    Posts
    2,353
    Rep Power
    117
    This code is not very well written. The request.getCookies() method returns null if there are no cookies, therefore one should check to see if it is null before processing

    Code:
    // The name of the cookie being stored on the client.
    Cookie cookieUid = null;
    
    // If it doesn't exist, use this as the NAME part of NAME=VALUE
    String cookieName = "user_id3";
    int cookieFound = 0;
    int sessionFound = 0;
    
    // This will store the value of the cookie
    String tempString;
    int count = 0; // just a counter
    
    
    // Request all the client cookies
    Cookie[] cookies = request.getCookies();
    
    // Go through the array looking for our cookie
    if(cookies != null) {
    	for(int i = 0; i < cookies.length; i++)
    	{
    		cookieUid = cookies[i];
    		if (cookieName.equals(cookieUid.getName()))
    		{
    			cookieFound = 1;
    			break;
    		}
    	}
    }

IMN logo majestic logo threadwatch logo seochat tools logo