JSP Cookies


What is a cookie?


Cookie a small data file reside in user’s system. Cookie is made by web server to identify users. When user do any request send to web server and web server know information of user by these cookie. After process request, web server response back to request by knowing through this cookie. JSP provides cookie classes,javax.servlet.http.Cookie, by this classes we can create and retrieve cookie. Once we set value in cookie, it lived until cookie gets expired. Cookie plays a big role in session, because maximum session is tracked by cookie in JSP.

1. JSP Example of creating Cookie

createCookie.jsp
 

<%@ page contentType="text/html; charset=iso-8859-1" language="java" %>
<html>
<body>
<form name="frm" method="get" action="createNewCookie.jsp">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td width="22%">&nbsp;</td>
    <td width="78%">&nbsp;</td>
    </tr>
  <tr>
    <td>Cookie value Set </td>
    <td><input type="text" name="cookieSet" /></td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td><input type="submit" name="submit" value="Submit"></td>
    </tr>
  <tr>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    </tr>
</table>
</form>
</body>
</html>
createNewCookie.jsp
 
<%@ page language="java" import="java.util.*"%>
<%
String cookieSet=request.getParameter("cookieSet");

Cookie cookie = new Cookie ("cookieSet",cookieSet);
response.addCookie(cookie);
%>

<html>
<head>
<title>Cookie Create Example</title>
</head>
<body>
    <%
   Cookie[] cookies = request.getCookies();
    
    for (int i=0; i<cookies.length; i++) {
      out.println(cookies[i].getName()+" : "+cookies[i].getValue()+"<br/>");
    }
    %>
</body>
</html>

Cookie cookie = new Cookie ("cookieSet",cookieSet);
We are creating new object of cookie class.
Here new Cookie(“Key”, “value”);
Then we are adding in cookie of response object.
response.addCookie(cookie); This is adding in cookie object new data.


Expire JSP cookie

Cookie cookie = new Cookie ("cookieSet",cookieSet);
cookie setMaxAge(0);

This will expire cookie.,with 0 second. We can set cookie age who long is reside for user.

Retrieve cookie from JSP

Cookie is in array object, we need to get in request.getCookies() of array.
Cookie[] cookies = request.getCookies();
for (int i=0; i<cookies.length; i++) {
      out.println(cookies[i].getName()+" : "+cookies[i].getValue()+"<br/>");
}



Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email