Read Cookies in Servlet

In this example, we will show you simple program about how to read cookies in servlet. The example program has been tested with Google Chrome browser and output shared in the below post.

Note: Before going to proceed with this example make sure that, you have already created cookies using servlet. We assume that you have created cookies and Its available in the browser already.

Servlet Class (MyCookieServlet.java)

package com.dineshkrish.servlet;
import java.io.IOException;
import java.io.PrintWriter;
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 {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/html");
// getting all cookies as array from request object
Cookie[] cookies = request.getCookies();
out.println("<ul>");
// iterating cookies array
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
out.println("<li>"+cookies[i].getName()+" - "+cookies[i].getValue()+"</li>");
}
}
out.println("</ul>");
out.close();
}
}

Configuration File (web.xml)

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<servlet>
<servlet-name>ReadCookies</servlet-name>
<servlet-class>com.dineshkrish.servlet.MyCookieServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ReadCookies</servlet-name>
<url-pattern>/readCookies</url-pattern>
</servlet-mapping>
</web-app>

Output

Read Cookies in Servlet

References

1. How to Create Cookies in Servlet
2. Java EE HttpServletRequest Interface
3. Java EE HttpServletResponse Interface
4. Java EE ServletException Class
5. Java IOException Class
6. Java EE Cookie Class

Tags:

No responses yet

Leave a Reply

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