JSP Cookie Handling

Cookie is a small piece of information sent by server to recognize the user. This information is stored at client side in the textual form.

In JSP, cookie is an object of javax.servlet.http.Cookie class. This object is used widely for session management purposes.

Methods of JSP Cookie

Some of the important method of cookie are as follows: -

  • void setMaxAge(int expiry): - This method is used to set the expiry time of cookie. Here, time is represent in the form of seconds.
  • void getMaxAge(): - This method returns the declared time of cookie after which it will expire.
  • String getName(): - This method returns the name of the cookie.
  • void setValue(String value): - This method is used to set associate the value with cookie.
  • String getValue(): - This method returns the value associated with the cookie.

Example of JSP Cookie assessment

Index.jsp

<html>
<body>
<%
String opt="Servlet";
Cookie[] ck=request.getCookies();
if(ck!=null)
{
    for(Cookie temp:ck)
    {
        if("technology".equals(temp.getName()))
        {
        opt=temp.getValue();
        break;
    }
}}
%>
<center>
<h2>Tutorial and Examples</h2>
<%=opt+" is a Java Based Technology." %>
<%="Our website provides enhanced level tutorials for "+opt %>
<br>
<a href="selection.jsp">Further assessment</a>
</center>
</body>
</html>

Selection.jsp

<html>
<body>
<center>
Select the technology
<form action="cookiepage.jsp">
<select name="tech">
<option>Servlet</option>
<option>JSP</option>
<option>JavaScript</option>
</select>
<br>
<input type="submit" value="submit">
</form>
</center>
</body>
</html>

Cookiepage.jsp

<html>
<body>
<center>
<%
String s=request.getParameter("tech");
Cookie c=new Cookie("technology",s);
c.setMaxAge(60);
response.addCookie(c);
%>
<h2>Thank you for selection</h2> <br>
<a href="index.jsp">Main page</a>
</center>
</body>
</html>
Output: