Edit Edit

Java Servlet FAQ


How do you send a cookie to the browser?


Create a new Cookie class and call the HttpServletResponse class' addCookie() function. The constructor for Cookie has the prototype:

public Cookie(String name, String value)

and addCookie()'s prototype is:

public void addCookie(Cookie cookie)

For example, if you wanted to save the customer's name to a cookie after he logs in, so that you can display his name the next time he hits your welcome page, the servlet would look like this:

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

public class Login extends HttpServlet {

    public void doGet(HttpServletRequest req, HttpServletResponse res)
                      throws ServletException, IOException
    {

       // the customer name is passed in through a form from the
       // login page
       String customer_name = req.getParameter("nameparam");

       // create a cookie for the customer name
       Cookie cookie = new Cookie("CustomerName", customer_name);

       // send the cookie to the browser in the response
       res.addCookie(cookie);

    }
}



Last updated 12/24/1999 06:00:59 PM