How do I send cookies from a client to a servlet?
Author: Deron Eriksson
Description: This Java tutorial describes how to send cookies from a client to a servlet.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 1.5.1 || Tomcat 5.5.20


Page:    1 2 >

If you are writing JavaSW code to connect to a web server (or servletW container), you can send cookiesW to the server by setting a CookieW request property on a URLConnection object. This is demonstrated in this tutorial.

Let's create a test project that features a servlet and a client that will make a request from that servlet, passing two cookies in the request to the servlet. This project features a web.xmlW file, the CookieTestServlet class, and the CookieTestClient class.

'cookie-test' project

The web.xml file is shown below. Notice that /test maps to the CookieTestServlet.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="cookie-test" version="2.4"
	xmlns="http://java.sun.com/xml/ns/j2ee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
	<servlet>
		<servlet-name>CookieTestServlet</servlet-name>
		<servlet-class>test.CookieTestServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>CookieTestServlet</servlet-name>
		<url-pattern>/test</url-pattern>
	</servlet-mapping>
</web-app>

The CookieTestServlet class is shown next. When a request is made of the servlet, it displays the message "This is the Cookie Test Servlet". If the request contains any cookies, the names and the values of the cookies are displayed.

CookieTestServlet.java

package test;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Servlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieTestServlet extends HttpServlet implements Servlet {

	private static final long serialVersionUID = 1L;

	public CookieTestServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("This is the Cookie Test Servlet");
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (int i = 0; i < cookies.length; i++) {
				Cookie cookie = cookies[i];
				String cookieName = cookie.getName();
				String cookieValue = cookie.getValue();
				out.println("Cookie Name: " + cookieName + 
					", Cookie Value: " + cookieValue);
			}
		} else {
			out.println("No cookies were found in the request");
		}
	}

}

The CookieTestClient class creates a URLConnection based on the URL "http://localhost:8080/cookie-test/test", which is the URL to the CookieTestServlet. Next, two cookies are set on the request via the setRequestProperty method with the "Cookie" property. Notice that two cookies are set. Each cookieW name is followed by an equal sign followed by the cookie value, and a semicolon separates the two cookies. The input stream from the servlet's response is fed into a StringBuffer, which is sent to standard output.

CookieTestClient.java

package test;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class CookieTestClient {

	public static void main(String[] args) {
		try {
			URL url = new URL("http://localhost:8080/cookie-test/test");
			URLConnection conn = url.openConnection();
			conn.setRequestProperty("Cookie", 
				"testCookie1=hello_there;testCookie2=goodbye_there");
			conn.connect();
			InputStream is = conn.getInputStream();
			StringBuffer sb = new StringBuffer();
			InputStreamReader isr = new InputStreamReader(is);
			int numCharsRead;
			char[] charArray = new char[1024];
			while ((numCharsRead = isr.read(charArray)) > 0) {
				sb.append(charArray, 0, numCharsRead);
			}
			System.out.println("CLIENT RECEIVED: " + sb.toString());
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

(Continued on page 2)

Page:    1 2 >