How do you set cookies in the JSP?

Setting cookies with JSP involves three steps −

Step 1: Creating a Cookie object

You call the Cookie constructor with a cookie name and a cookie value, both of which are strings.

Cookie cookie = new Cookie("key","value");

Keep in mind, neither the name nor the value should contain white space or any of the following characters −

[ ] ( ) = , " / ? @ : ;

Step 2: Setting the maximum age

You use setMaxAge to specify how long (in seconds) the cookie should be valid. The following code will set up a cookie for 24 hours.


Step 3: Sending the Cookie into the HTTP response headers

You use response.addCookie to add cookies in the HTTP response header as follows



 Live Demo

   // Create cookies for first and last names.
   Cookie firstName = new Cookie("first_name", request.getParameter("first_name"));
   Cookie lastName = new Cookie("last_name", request.getParameter("last_name"));

   // Set expiry date after 24 Hrs for both the cookies.

   // Add both the cookies in the response header.
   response.addCookie( firstName );
   response.addCookie( lastName );
      <title>Setting Cookies</title>
         <h1>Setting Cookies</h1>
         <li><p><b>First Name:</b>
            <%= request.getParameter("first_name")%>
         <li><p><b>Last Name:</b>
            <%= request.getParameter("last_name")%>

Let us put the above code in main.jsp file and use it in the following HTML page −

 Live Demo

      <form action = "main.jsp" method = "GET">
         First Name: <input type = "text" name = "first_name">
         <br />
         Last Name: <input type = "text" name = "last_name" />
         <input type = "submit" value = "Submit" />

Keep the above HTML content in a file hello.jsp and put hello.jsp and main.jsp in <Tomcat-installation-directory>/webapps/ROOT directory. When you will access  http://localhost:8080/hello.jsp, here is the actual output of the above form.


Try to enter the First Name and the Last Name and then click the submit button. This will display the first name and the last name on your screen and will also set two cookies firstName and lastName. These cookies will be passed back to the server when the next time you click the Submit button.

Samual Sam
Samual Sam

Learning faster. Every day.