I have designed a jsp which has the following code :
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Form Cookie</title>
</head>
<body>
<form action="http://localhost:8080/FormCookie/AddValue">
Name : <input type="text" name="name"><br>
Age : <input type="text" name="age">
<input type="submit" value="submit">
</form>
</body>
</html>
Secondly i created a servlet which retrieves the name and age that user enters and stores it in the cookie. hers the code
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name= request.getParameter("name");
String age= request.getParameter("age");
Cookie c= new Cookie("myname", name);
Cookie c1= new Cookie("age", age);
response.addCookie(c);
response.addCookie(c1);
c.setMaxAge(20);
c1.setMaxAge(20);
}
and finally i created a servlet which simply prints the values stored in the cookie file
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Cookie[] cookie = request.getCookies();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
for(int i=0; i<cookie.length;i++)
{
if(cookie==null)
{
out.println("No cookie found");
}
else if(cookie[i].getName().equals("myname"))
{
out.println("Name is "+cookie[i].getValue());
}
else if(cookie[i].getName().equals("age"))
{
out.println("age is "+cookie[i].getValue());
}
}
out.close();
}
Now there is nowhere problem in printing the values of the cookie file infact this code works well but when i close up my browser am unable to get that values stored in the cookie file and also it gives me nullpointerxception though i have used a if condition specifying (c==null){ blah blah }. so i just want to know why am not getting printed in the browser "no cookie found" and also when i close my browser and open it for the next time, i should be able to get the value stored in the cookie......