How to access the Cookies at the Client site

Here’s a example to access the Cookies at the previous article “simple cookie example

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 ServletDemoCookie extends HttpServlet{
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws IOException{
	
		response.setContentType("text/html");
		PrintWriter pw = response.getWriter();
		
		Cookie[] cookie = request.getCookies();
		pw.println("All Cookies in your browsers");
		
		for(Cookie obj : cookie){
			
			if(obj.getName().equals("url")){
				pw.println(obj.getName() + " : " + obj.getValue());
				break;
			}
		}
	}
}

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>PrintCookieServlet</servlet-name>
		<servlet-class>com.mkyong.ServletDemoCookie</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>PrintCookieServlet</servlet-name>
		<url-pattern>/printCookie</url-pattern>
	</servlet-mapping>
	
</web-app>

The above example will retrieve the cookie information at client site and check whether it’s contains the “url” name.

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
0 Comment authors
A simple cookie example in servlet | Servlet Recent comment authors
newest oldest most voted
trackback
A simple cookie example in servlet | Servlet

[…] 2. Please check here to study How to access the Cookies […]