Using Cookies 
Now, let’s develop a servlet that illustrates how to use cookies. The servlet is invoked when a form on a Web page is submitted. The example contains three files, as summarized hei e:


Description .
Allows a user to specify a value for the cookie named MyCookic Processes the submission of
Displays cookie values

The HTML source code for Add Cookic.htm is shown in the following listing. This .puge contains a text field in which a value can be entered. The page also includes a submit button. When this b~tton is pressed, the value in the text field is sent to Add Cookies Servlet via an rt;.rP POST request. The source code for Add’ is shown in the following listing. It gets the value of the parameter named “data”. It then creates a Cookie object that has the name “MyCookie” and contains the value of the “data” parameter. The cookie is then added to the header of the HITP response via the addCookie{ ) method. A feedback message is then written to the browser. The source code for Get Cookies is shown in the following listing.’ It invokes the gel Cookies( ) method to rend nny cookies that are included in the HTIP GET request. The names and values of these cookies are then written to the HTTP response. Observe that the get Name () and methods arc called to obtain this information. Compile the servlet and perform these steps:

1. Start the servletrunner.
2. Display Add’Cookie.htrn In a browser.
3. Enter a value for MyCookie.
4. Submit the Web page.

After you complete these steps, observe that a teed back message is displayed by the browser.
Next, request the fOLLowing URL via the browser


Observe that the name and value of the cookie arc displayed in the browser. In this example, an expiration date is not explicitly assigned to the cookie via the setMaxAgc( ) method of Cookie. Therefore, the cookie expires when the browser session ends. You can experiment with this method and observe that the cookie is then saved to the disk on the client machine

[vfb id=1]

Share This