Java Servlet Cookies

What is Cookies?

  • Cookie data comes in name-value pairs.
  • It is easy to construct a cookie:
    ...
    // Constructor: Cookie(String name, String value)
    ...
    Cookie cookie = new Cookie("ID", "123");
    ...
  • You will get the Cookies from the HttpServletRequest interface :
    ...
    // HttpServletRequest interface :  Cookie[] getCookies()
    ...
    Cookie[]  cookies= request.getCookies();
    if (cookies ! = null) {
      for (int i = 0; i < cookies.length; i++) {
        String name = cookies[i].getName();
        String value = cookies[i].getValue();
      }
    }
    ...
  • You can add Cookies to the HttpServletResponse interface :
    ...
    // HttpServletResponse interface:  void addCookie(Cookie cookie)
    ...
    Cookie cookie = new Cookie("ID", "123");
    response.addCookie(cookie);
     ...

© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.