Handling cookies

Cookies are text files stored on the client's computer. They store different information which can be using for tracking-purpose such as identifying a returned user. In this tutorial, we will create, read and destroy cookies using Java servlet.

Creating cookies

  1. Open the servletlabs project in the previous tutorial.
  2. Right click on the WebContent folder, select New→File. Name the file: cookie.html.
  3. Insert the following codes between the <body> tags:

    <form method="GET" action="/servletlabs/SetCookie">
    First name: <input type="text" name="firstname" /> <br>
    Last name: <input type="text" name="lastname" /> <br>
    <input type="submit" />
    </form>
  4. Save the file.
  5. Right click on the servletlabs project, select New→servlet. Name the package as: cookie.servlet and the class as: SetCookie.
  6. Insert the following codes into the doGet(…) functions:

    	      // Create cookies for first and last names, using:
    	      // Cookie cookiename = new Cookie("key","value");
    	      Cookie firstName = new Cookie("first",
    	                      request.getParameter("firstname"));
    	      Cookie lastName = new Cookie("last",
    	                      request.getParameter("lastname"));
     
    	      // Set expiry date after 24 Hrs for both the cookies.
    	      firstName.setMaxAge(60*60*24); 
    	      lastName.setMaxAge(60*60*24); 
     
    	      // Add both the cookies in the response header.
    	      response.addCookie( firstName );
    	      response.addCookie( lastName );
     
    	      // Set response content type
    	      response.setContentType("text/html");
     
    	      PrintWriter out = response.getWriter();
    	      String title = "Setting Cookies Example";
    	      String docType =
    	      "<!doctype html public \"-//w3c//dtd html 4.0 " +
    	      "transitional//en\">\n";
    	      out.println(docType +
    	                "<html>\n" +
    	                "<head><title>" + title + "</title></head>\n" +
    	                "<body bgcolor=\"#f0f0f0\">\n" +
    	                "<h1 align=\"center\">" + title + "</h1>\n" +
    	                "<ul>\n" +
    	                "  <li><b>First Name</b>: "
    	                + request.getParameter("firstname") + "\n" +
    	                "  <li><b>Last Name</b>: "
    	                + request.getParameter("lastname") + "\n" +
    	                "</ul>\n" +
    	                "</body></html>");
  7. Some errors appear because of the missing libraries. Click on the symbols x on the left and select to import the suggested libraries. Or you can manually insert the following lines in the import section.

    import javax.servlet.http.Cookie;
    import java.io.PrintWriter;
  8. Save the file.
  9. Right click on the cookie.html file. Select Run→Run on Server. The file cookie.html will be opened at: http://localhost:8080/servletlabs/cookie.html
  10. Type your name and click Submit Query


  11. The SetCookie servlet will return your information with two declared cookies. These cookies are stored in your computer.


  12. You can view these cookies using your web browser.

Reading cookies

  1. Right click on the cookie.servlet package, select New→Servlet. Name it ReadCookie.
  2. Insert the following codes in the doGet(…) function

    	      Cookie cookie = null;
    	      Cookie[] cookies = null;
    	      // Get an array of Cookies associated with this domain
    	      cookies = request.getCookies();
     
    	      // Set response content type
    	      response.setContentType("text/html");
     
    	      PrintWriter out = response.getWriter();
    	      String title = "Reading Cookies Example";
    	      String docType =
    	      "<!doctype html public \"-//w3c//dtd html 4.0 " +
    	      "transitional//en\">\n";
    	      out.println(docType +
    	                "<html>\n" +
    	                "<head><title>" + title + "</title></head>\n" +
    	                "<body>\n" );
    	      if( cookies != null ){
    	         out.println("<h2> Found Cookies Name and Value</h2>");
    	         for (int i = 0; i < cookies.length; i++){
    	            cookie = cookies[i];
    	            out.print("Name : " + cookie.getName( ) + ",  ");
    	            out.print("Value: " + cookie.getValue( )+" <br/>");
    	         }
    	      }else{
    	          out.println(
    	            "<h2>No cookies founds</h2>");
    	      }
    	      out.println("</body>");
    	      out.println("</html>");
  3. Correct the missing libraries to fix all generated errors.
  4. Save the file and restart your Tomcat.
  5. Open http://localhost:8080/servletlabs/ReadCookie on your web browser. You'll see the cookies that you set.


Exercises

  1. To delete a cookie, we set the max age of the cookie is 0. So, could you please create another Servlet that can delete your created cookies ?
  2. Create another servlet that count the number of visits using cookies.
  3. Disable cookies option on your web browser and re-run the servlet created in exercise 2.
  4. Modify the tutorial to store user's names at the server side and just a unique token string at the client side. The servlet will return proper names according to the received token string in the client's request.
teaching_assistant/servlet-jsp/servlet-cookie.txt · Last modified: 2013/07/08 08:44 (external edit)
Back to top
CC Attribution-Share Alike 4.0 International
chimeric.de = chi`s home Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0