# Cookies in Java

In 
Published 2022-12-03

This tutorial explains to you how the cookies are used in a Java Application.

HTTP Cookies are little pieces of data which is send from the browser to the application server and from the application server to the browser. The server use this information (cookie) for identifying the request/ the user (for session management). This data exchange happens when a cookie is created. If the cookie is not created, no cookie is sent by the browser.

The cookies could be created by JavaScript directly on the browser or by a servlet on the server. When the cookie is created by the server it will send a response to the browser containing the cookie (in the header response). In this case the browser will create a cookie locally and will send that cookie to that website if the cookie is not expired (when the cookie is expired it will be deleted from the browser and will not be used until another cookie will be created instead).

For showing this behavior, I will create a Dynamic Web Application under Eclipse and I will use WildFly as Java Application Server and Google Chrome as browser.

First, here are the elements of the application:

  • 2 HTML page (the index.html and page2.html) :
index.html
<html>
 <head>
    <meta charset="ISO-8859-1">
    <title>From this page you call a Java servlet using POST Method</title>
 </head>
 <body>
    <p> This is the <b> index.html </b> page. </p>
      
    <form action="MyJavaServlet" method="POST">
       Name: <input type="text" name="name">
       <br>
       Telephone#: <input type="text" name="telephone">
       <input type="submit" value="Submit">
    </form>
    
 
    <p style="margin-top: 10; margin-bottom: 0">Link to another HTML page: 
       <a href="http://localhost:8080/Java_cookies/page2.html">Page2.html</a></p>
 </body>
</html>
page2.html
<html>
 <head>
      <meta charset="ISO-8859-1">
      <title>From this page you call a Java servlet using POST Method</title>
 </head>
 <body>
      <p> This is the <b> page2.html </b> page. </p>
 
      <form action="MyJavaServlet" method="POST">
         Name: <input type="text" name="name">
         <br>
         Telephone#: <input type="text" name="telephone">
         <input type="submit" value="Submit">
      </form>
       
      <p style="margin-top: 10; margin-bottom: 0">Link to another HTML page: 
        <a href="http://localhost:8080/Java_cookies/index.html"> index.html</a></p>
 </body>
</html>
  • 1 Java servlet which create the cookie :
package servlets;
 
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.zip.GZIPOutputStream;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
/**
 * Servlet implementation class MyJavaServlet
 */
@WebServlet("/MyJavaServlet")
public class MyJavaServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
        
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MyJavaServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
 
    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // TODO Auto-generated method stub
 
        PrintWriter myResponse = response.getWriter();
         
        String message = "This is your response from a POST call. <br> The response is a Java Servlet !";
         
        Cookie name = new Cookie("name",  request.getParameter("name"));
        
        // Set expiry date after 1 hour for this cookie.
        name.setMaxAge(60*60*2);
        name.setDomain("localhost");
        name.setPath("/");
         
        // Add the cookie to the response header.
        response.addCookie(name);
        
        myResponse.println( "\n" + 
             "<title> Example of using Java Servlet with POST Call Method !</title>\n" +
             "\n" +
             "<h2 align="\"center\"">" + message + "</h2>\n" +
             "<ul>\n" +
             "  <li><b>You entered the name </b>: "       + request.getParameter("name") + "\n" +
             "  </li><li><b>You entered the telephone# </b>: " + request.getParameter("telephone") + "\n" +
             "</li></ul>\n <p>   </p>  <p>Link to HTML page : "+
             "  <a href="http://localhost:8080/Java_cookies/page2.html">link</a></p> " +
             "");
    }
}

As you can see:

  • the cookie is created for the domain "localhost", but in real life you will have something like "mydomain.com";

  • the cookie has an expiration date: in my example that cookie will expire in 2 hours (however each time that servlet will be called, the expiration date will change);

  • the path "/" signify that the cookie will apply for all pages of that site.

Take a look at the following pictures.

In the picture above you can see that you are on the index.html page. When the page was requested a cookie was sent, but no cookie was received (but one cookie is still available for this site on the browser). This information is from the "Developer Tools".

In the picture above you can see that on Google Chrome you can click on the "i" icon to see information on the active cookies.

In the picture above you can see the index.html page. From this page you can navigate to page2.html, or you can press on "Submit" button to call the servlet which will create a cookie.

In the picture above you can see that a cookie exist for that site ("name=Helena"), but that Java servlet will change the name for that cookie (the name will be "Dan").