This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
The moose likes Web Component Certification (SCWCD/OCPJWCD) and the fly likes JSp with Cookies HFSJ pg 386 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

JavaRanch » Java Forums » Certification » Web Component Certification (SCWCD/OCPJWCD)
Bookmark "JSp with Cookies HFSJ pg 386" Watch "JSp with Cookies HFSJ pg 386" New topic

JSp with Cookies HFSJ pg 386

Mukunthan Shanmuganathan
Ranch Hand

Joined: Jul 24, 2007
Posts: 32

In order to check Cookies with JSP I wrote as follows,


package com.example;

import javax.servlet.*;
import javax.servlet.http.*;

public class CookieTest extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


PrintWriter out = response.getWriter();

String user = request.getParameter("username");

Cookie cookie = new Cookie("name",user);



RequestDispatcher view = request.getRequestDispatcher("result.jsp");





Cookie[] cookies = request.getKookies();

for( int i = 0 ; i < cookies.length ; i++ ) {

Cookie cook = cookies[i];

if ( (cook.getName()).equals("name") ) {


When I deploy and run I get a NullPointerException Why?

Dare to know!
Tarun Yadav
Ranch Hand

Joined: Sep 20, 2007
Posts: 134
Originally posted by Mukunthan Shanmuganathan:


That's right. Let's round all the kookies up and put them away!

Ok, but seriously, where exactly is the NPE? If you'd point out the line it would help determine what is causing the problem...this is pretty vague. And also, it looks like you're typing your code; please don't do that as it can mask errors and will be pretty frustrating for all involved.
Michael Ku
Ranch Hand

Joined: Apr 20, 2002
Posts: 510
You will need to round trip back to the browser to see the cookie. If you set the cookie into the response then, before you go back to the browser with the response and therefore set the cookie on the client, you go to the JSP, the cookie was never returned to the client and therefore will not be in the request.

When you make a second request to your web app, the cookie will be in the request.
Mukunthan Shanmuganathan
Ranch Hand

Joined: Jul 24, 2007
Posts: 32
Dear Tarun Yadav and Michael Ku,

Thank You.

Tarun Yadav,I apologize for writing the code here. I won't do it again.

Michael Ku, I understand your point.

Thank You very much both of you Guys.

I agree. Here's the link:
subject: JSp with Cookies HFSJ pg 386
jQuery in Action, 3rd edition