How to Create Cookies in Servlet

Create Cookies in Servlet

In this simple example, we will show you how to create cookies in servlet. This particular example has been tested with Google Chrome browser environment. The example source code has been explained step by step in the below post.

Servlet Code (MyCookieServlet.java)

package com.dineshkrish.servlet;

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

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

/**
 * 
 * @author Dinesh Krishnan
 *
 */

public class MyCookieServlet extends HttpServlet {

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

		PrintWriter out = response.getWriter();
		
		response.setContentType("text/html");
		
		// creating cookies
		Cookie nameCookie = new Cookie("name", "Dinesh Krishnan");
		Cookie emailCookie = new Cookie("emailId", "[email protected]");
		Cookie websiteCookie = new Cookie("website",  "http://www.dineshkrish.com");
		
		// adding the cookies to response
		response.addCookie(nameCookie);
		response.addCookie(emailCookie);
		response.addCookie(websiteCookie);
		
		out.println("<h1>Cookies has been sent successfully to client... :))</h1>");
		
	}

}

Configuration File (web.xml)

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">

	<servlet>
		<servlet-name>SendCookie</servlet-name>
		<servlet-class>com.dineshkrish.servlet.MyCookieServlet</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>SendCookie</servlet-name>
		<url-pattern>/sendCookie</url-pattern>
	</servlet-mapping>

</web-app>

Output

You can run the above example in the Google Chrome. Since the attached program has been tested with google chrome browser.

How to Create Cookies in Servlet

How do I check cookies are created?

Open Google Chrome -> Go to Settings in the Menu -> In Search Box (Type cookies) -> Go to Content Settings… -> Go to All Cookies and Site Data… -> then you can see Cookies and Site Data dialogue box, We also attached sample screen shot below.

Create Cookies in Servlet

References

1. Java EE HttpServletRequest Interface
2. Java EE HttpServletResponse Interface
3. Java EE ServletException Class
4. Java IOException Class
5. Java EE Cookie Class