I'm trying to run a simple servlet that counts the number of times a user visits the page using cookies but I'm getting the following error. I thought that NullPointerException was because there were no cookies at all in the browser. But after checking I found a couple of cookies existing.


This is the error I'm getting.

HTTP Status 500 -

type Exception report

message

description The server encountered an internal error () that prevented it from fulfilling this request.

exception

java.lang.NullPointerException
PageCount.doGet(PageCount.java:24)
javax.servlet.http.HttpServlet.service(HttpServlet.java:689)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
note The full stack trace of the root cause is available in the Apache Tomcat/5.5.12 logs.

Here's the program:

/* count the number of times a user visits a page
   if it's the first time: display a welcome message
   else print the number of times the page has been visited.
*/


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


public class PageCount extends HttpServlet
{
	protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException
	{
		res.setContentType("text/html");
		PrintWriter pw = res.getWriter();
		Cookie cur[] = req.getCookies();
		boolean cookieExists = false;
		
				
		for(int i=0; i<cur.length; i++)
			{
				Cookie c = cur[i];

				String name = c.getName();
	
				if(name=="myid")
					{
						cookieExists = true;
					}	
		
				else
					continue;
			}


		
		if(cookieExists == false)
			{	
				pw.println("Welcome to the world of AshxSlash");
				Cookie act = new Cookie("myid", "1");
			
			}
	
		else
			{
				for(int i=0; i<cur.length; i++)
					{			
						Cookie c = cur[i];
						String name = c.getName();

							if(name=="myid")
								{
								  String value = c.getValue();
								  int val = Integer.parseInt(value);
								  if(val==1)
								   {
								      pw.println("This is your "+val+"th visit");
								      int newval = val + 1;
								      c.setValue("newval");
								   }
								}
					}
			}
	}
}
}

java.lang.NullPointerException
PageCount.doGet(PageCount.java:24)

Look at line 24 and find the variable that has a null value. Then backtrack in the code to see why that variable does not have a non-null value.
If null is valid value, the you test for it before using the variable.

if(name=="myid")

Use the equals() method to compare Strings

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.