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.

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments