19.09.2015 Views

Prentice.Hall.Introduction.to.Java.Programming,.Brief.Version.9th.(2014).[sharethefiles.com]

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

javax.servlet.http.Cookie<br />

+Cookie(name: String, value: String)<br />

+getName(): String<br />

+getValue(): String<br />

+setValue(newValue: String): void<br />

+getMaxAge(): int<br />

+setMaxAge(expiration: int): void<br />

+getSecure(): boolean<br />

+setSecure(flag: boolean): void<br />

+getComment(): String<br />

+setComment(purpose: String): void<br />

Creates a cookie with the specified name-value pair.<br />

Returns the name of the cookie.<br />

Returns the value of the cookie.<br />

Assigns a new value <strong>to</strong> a cookie after the cookie is created.<br />

Returns the maximum age of the cookie, specified in seconds.<br />

Specifies the maximum age of the cookie. By default, this value is –1, which implies<br />

that the cookie persists until the browser exits. If you set this value <strong>to</strong> 0, the cookie<br />

is deleted.<br />

Returns true if the browser is sending cookies only over a secure pro<strong>to</strong>col.<br />

Indicates <strong>to</strong> the browser whether the cookie should only be sent using a secure<br />

pro<strong>to</strong>col, such as HTTPS or SSL.<br />

Returns the <strong>com</strong>ment describing the purpose of this cookie, or null if the cookie has<br />

no <strong>com</strong>ment.<br />

Sets the <strong>com</strong>ment for this cookie.<br />

Figure 42.23<br />

Cookie s<strong>to</strong>res a name/value pair and other information about the<br />

cookie.<br />

To send a cookie <strong>to</strong> the browser, use the addCookie method in the<br />

HttpServletResponse class, as shown below:<br />

response.addCookie(cookie);<br />

where response is an instance of HttpServletResponse.<br />

To obtain cookies from a browser, use<br />

request.getCookies();<br />

where request is an instance of HttpServletRequest.<br />

To demonstrate the use of cookies, let us create an example that<br />

ac<strong>com</strong>plishes the same task as Listing 42.9, Registration.java. Instead<br />

of using hidden values for session tracking, it uses cookies.<br />

Create the servlet named RegistrationWithHttpCookie in Listing 42.10.<br />

Create an HTML file named RegistrationWithCookie.html that is identical<br />

<strong>to</strong> Registration.html except that the action is replaced by<br />

RegistrationWithCookieH..<br />

Listing 42.10 RegistrationWithCookie.java<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

package chapter42;<br />

import javax.servlet.*;<br />

import javax.servlet.http.*;<br />

import java.io.*;<br />

import java.sql.*;<br />

33

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!