A simple cookie example in servlet

Here’s a simple Cookie example in Servlet

Java Source


package com.mkyong;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletDemo extends HttpServlet{
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws IOException{
	
		response.setContentType("text/html");
		PrintWriter pw = response.getWriter();
		
		Cookie cookie = new Cookie("url","mkyong dot com");
		cookie.setMaxAge(60*60); //1 hour
		response.addCookie(cookie);
		
		pw.println("Cookies created");
	}
}

web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" 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">

	<display-name>servletdemo</display-name>
	
	<servlet>
		<servlet-name>ServletName</servlet-name>
		<servlet-class>com.mkyong.ServletDemo</servlet-class>
	</servlet>
	
	<servlet-mapping>
		<servlet-name>ServletName</servlet-name>
		<url-pattern>/Demo</url-pattern>
	</servlet-mapping>

</web-app>

The above example will create a simple Cookie with a name “url” and value “mkyong dot com”, time to live is one hour, and store in client computer.

Run It

Deploy and execute the servlet in Firefox and you can check the Cookies is created in Firefox.

servlet-cookies

1. Please check here to study where does FireFox stored the Cookies

2. Please check here to study How to access the Cookies

14 comments on “A simple cookie example in servlet

  1. Cookies gives error when add record
    “An invalid character [10] was present in the Cookie value”

    Reply
  2. its awesome tutorial, please send me your gmail or your email account address.

    Reply
  3. I have a question. This is not related to cookies topic.
    how do interface perform some task without having body in java. For example
    RequestDispatcher rd=request.getRequestDispatcher(“Login.html”);
    rd.include(request, response);

    My doubt is include method is not implemented. so how it is performing its tasks?????
    I am new to java

    Reply
  4. I feel better to understand this cookie concept….thanks a lot…

    Reply
  5. how to create array of cookie and how how to commpare two cookies……..

    Reply
  6. this good example for me……thanks…..and also post all update topic ….avd*

    Reply

Leave a Comment

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