Using Cookies Java Help

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:

File
AddCookie.htm
AddCookieScrvlet.java
GetCookiesServlet.java

Description .
Allows a user to specify a value for the cookie named MyCookic Processes the submission of
AddCookic.htm
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’Cookicfiervlet.java 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 Servlet.java 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

http://localhosL:aOaO/servlet/GecCookiesS~rvlut

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

JavaHelpOnline.com

  • Feel free to send us an inquiry, we will reply back in hours.
 

Verification

Posted on September 18, 2014 in Servlets

Share the Story

About the Author

Back to Top
Share This