How do I send cookies from a servlet?


HTTP is a stateless protocol, which makes tracking user actions difficult. One solution is to use a cookie, which is a small piece of data sent by a web browser every time it requests a page from a particular site. Servlets, and CGI scripts, can send cookies when a HTTP request is made - though as always, there is no guarantee the browser will accept it.

Cookies are represented by the javax.servlet.http.Cookie class. Cookie has a single constructor, which takes two strings (a key and a value). 

// Create a new cookie
Cookie cookie = new Cookie ("counter", "1");

Adding a cookie to a browser is easy. Cookies are sent as part of a HTTPServletResponse, using the addCookie( Cookie ) method. You can call this method multiple times, but remember that most browsers impose a limit of ten cookies, and 4096 bytes of data per hostname.

public void doGet (HttpServletRequest request, HttpServletResponse response)
 throws IOException
	response.addCookie(new Cookie("cookie_name", "cookie_value"));