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 (

package com.dineshkrish.servlet;
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 {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
// creating cookies
Cookie nameCookie = new Cookie("name", "Dinesh Krishnan");
Cookie emailCookie = new Cookie("emailId", "");
Cookie websiteCookie = new Cookie("website",  "");
// adding the cookies to response
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=""
id="WebApp_ID" version="3.0">


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


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


No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *