How to handle cookies in JSP?

In the previous article, we have seen How to write filters in JSP. In this article, We will discuss Cookies and the Handling of cookies in JSP, the best way to store and retrieve cookies in JSP.

Today, many websites use string text called cookies to store persistent client-side state between connection. Cookies are helpful for storing session ID, shopping cart contents, login credentials, etc.

What are Cookies?

Cookies are data packets that the computer receives, then sends back without altering it.

  • Whenever you visit any website, the website sends the cookie to your computer, your computer stores in the file located inside your web browser.

  • It is helpful in keeping track of your website visitors.
  • As we see now, we have different passwords and we cannot handle so many passwords so, whenever we log in, the browser asks us to save the password and then we click on save.

The Set-Cookie HTTP response header sends a cookie from the server to the client. A cookie looks like this

Set-Cookie <cookie-name>=<cookie-value>

This shows the server sending header to tell clients to store a pair of cookies.

HTTP/2.0 404 NOT FOUND
Content-Type:text/html
Set-Cookie:cookie_1=abc
Set-Cookie:cookie_2=abc1234
[Page content]

Whenever client request to the server, the browser send back all previously-stored cookie to the server in the following way

GET/hello.page HTTP/2.0
Host:www.abc.org
Cookie:cookie_1=abc,cookie_2=abc1234

The Lifetime of cookie

  • Session Cookies: This is deleted when the current session ends.
  • Permanent Cookies: This is deleted as per the specified Expired date attribute.
Set-Cookie: id=1234; Expires=Fri, 10 Feb 2022 :15:00 GMT;

Methods of JSP Cookies

  • public void setDomain(String pattern): This method sets the domain to which cookie applies. for eg https://codedec.com/
  • public String getDomain(): This method returns the domain to which the cookie applies.
  • public void setMaxAge(int expiry): This method sets the expiry of the cookie.
  • public int getMaxAge(): This method returns the age of the cookie specified in second.
  • public String getName(): This method returns the name of the cookie.
  • public void setValue(String value): This method sets the values associate with cookies.
  • public String getValue(): This method returns the value associated with the cookie.
  • public void setPath(String uri): This method sets the path to which cookies applied.
  • public String getPath(): This method returns the path to which cookies apply.
  • public void setSecure(boolean flag): This method sets the value indicating whether the cookie should only be sent over an encrypted network.
  • public void setComment(String purpose): This method sets the comment for the cookie.
  • public void getComment(): This method returns the comment of the cookie.

How to set Cookies in JSP?

  • Create a cookie
Cookie cookie=new Cookie("key","value");
  • Set the maximum age
cookie.setMaxAge(60*60*24)
  • Send the cookie
response.addCookie(cookie);

How to handle Cookies in JSP?

Let’s see an example of Remember username and password in JSP using cookies.

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
  <%
    Cookie[] cookies = request.getCookies();
    String username = "";
    String password = "";
    if (cookies != null) {
      for (int i = 0; i < cookies.length; i++) {
        Cookie cookie1 = cookies[i];
        if (cookie1.getName().equals("cookie-username")) {
          username = cookie1.getValue();
        } else if (cookie1.getName().equals("cookie-password")) {
          password = cookie1.getValue();
        }
      }
    }
  %>
  <form action="welcome.jsp">
    <table bgcolor="#A5D8F3">
      <tr>
        <td>Username</td>
        <td><input type="text" name="uname" value="<%=username%>"></td>
      </tr>
      <tr>
        <td>Password</td>
        <td><input type="password" name="pass" value="<%=password%>"></td>
      </tr>
      <tr>
        <td>Remember me</td>
        <td><input type="checkbox" name="remember" value="true"></td>
      </tr>
      <tr align="center">
        <td><input type="submit" value="Submit"></td>
      </tr>
    </table>
  </form>


</body>
</html>

welcome.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
  <%
String name=request.getParameter("uname");
String pass=request.getParameter("pass");
String remember=request.getParameter("remember");
out.print("Username "+name+"<br>Password  "+pass);
if(remember!=null)
{
  Cookie user= new Cookie("cookie-username",name);
  Cookie passw=new Cookie("cookie-password",pass);
  user.setMaxAge(24*60*60);
  passw.setMaxAge(24*60*60);
  response.addCookie(user);
  response.addCookie(passw);
}
%>
</body>
</html>

Output

Once again access the index.jsp page this time the username and password field will be auto-filled.

Uses of Cookie

  • Cookies are able to keep track of the website.
  • It is on the client-side.
  • Use to store login information of the user.

Thus we have seen How to Handle cookies on the JSP page with a simple example.

In the next article of the tutorial, we will discuss How to handle sessions on the JSP page with a simple example.