JSP: deal with cookie : Cookie « JSP « Java






JSP: deal with cookie

<%@ page import="javax.servlet.http.Cookie" %>

<html>
<head>
<title>This page leaves a cookie</title>
</head>

<body>
<h1>Cookies</h1>

<%
  Cookie[] allCookies = request.getCookies();
  Cookie ourCookie = null;
  if (allCookies!=null)
  {
    for (int i=0; i<allCookies.length; i++)
    {
      if (allCookies[i].getName().equals("TestCookie"))
        {
          ourCookie = allCookies[i];
        }
    }
  }

  if (ourCookie == null)
  {
    Cookie cookie = new Cookie("TestCookie", "hello from cookie");
    //cookie.setMaxAge(1800);
    //cookie.setDomain("alex:8080");
    cookie.setPath("/");
    response.addCookie(cookie);
%>
    A cookie has been added to your machine!
    <br>Select refresh to see the details of this cookie.

<%
  }
  else
  {
%>
    The following cookie was added earlier to your machine:
    <br>Version: <%=ourCookie.getVersion() %>
    <br>Name: <%=ourCookie.getName() %>
    <br>Value: <%=ourCookie.getValue() %>
    <br>MaxAge: <%=ourCookie.getMaxAge() %>
<%
  }
%>

</body>
</html>
           
       








Related examples in the same category

1.JSP Create and List Cookie
2.JSP List All Cookie
3.Setting a Cookie
4.Setting and Reading Cookies
5.Deal with the cookie
6.Cookie display in a JSP page