Saturday, 15th October 2011
Follow WikiJava on twitter now. @Wikijava

Read a Cookie from a servlet

From WikiJava

Jump to: navigation, search


This article contains a simple Servlet that prints out all the cookies sent from the client with the HTTP request.

Contents

the article

This example uses the:

Cookie[] request.getCookies()

and

Cookie.getName() 
Cookie.getValue()

to retrieve the cookies information from the request object.

MyServlet

import javax.servlet.*;
import javax.servlet.http.*;
 
public class MyServlet extends HttpServlet {
  public void doPost
    (HttpServletRequest req, HttpServletResponse res) {
     Cookie[] theCookies = request.getCookies();
     if (theCookies != null) {
        java.io.PrintWriter out = res.getWriter();
        for (int i =0; i< cookies.length; i++) {
           Cookie aCookie = theCookies[i];
           out.println 
             ("Name : " + aCookie.getName() 
               + " Value: " + aCookie.getValue());
           }
        }
    }
 
  public void doGet(HttpServletRequest req, HttpServletResponse res) {
    doPost(req, res);
    }
 
}

See Also

Real's Java How To

Comments from the users

To be notified via mail on the updates of this discussion you can login and click on watch at the top of the page


Comments on wikijava are disabled now, cause excessive spam.