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.

1. Please check here to study where does FireFox stored the Cookies
2. Please check here to study How to access the Cookies
[...] How to access the Cookies at the Client site Written on December 4, 2009 at 9:42 pm by mkyong Here’s a example to access the Cookies at the previous article “simple cookie example” [...]