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");
}
}
}
}
}
}
}