↑
Main Page
Cookies on the server
Cookies on the server
Of course, using cookies for client-server communication requires additional logic on the server. Server-
side technologies such as JSP, ASP.NET, and PHP provide built-in functionality to read, write, and other-
wise manipulate cookies. Using JavaScript and one of these server-side languages, you can pass data
back and forth using cookies.
JSP
Java Server Pages (JSP) provides a very easy interface for handling cookies. The
request
object, which is
instantiated automatically when a JSP is executed, has a method called
getCookies()
that returns an
array of
Cookie
objects. Each
Cookie
object has the following methods (from the Javadoc documentation):
?
getComment()
— Returns the comment describing the purpose of this cookie, or
null
if the
cookie has no comment
?
getDomain()
— Returns the domain name set for this cookie
?
getMaxAge()
— Returns the maximum age of the cookie, specified in seconds; by default, -1
indicates the cookie will persist until browser shutdown.
?
getName()
— Returns the name of the cookie
?
getPath()
— Returns the path on the server to which the browser returns this cookie
?
getSecure()
— Returns
true
if the browser is sending cookies only over a secure protocol, or
false
if the browser can send cookies using any protocol.
?
getValue()
— Returns the value of the cookie
?
getVersion()
— Returns the version of the protocol this cookie complies with
?
setComment(String purpose)
— Specifies a comment that describes a cookie’s purpose.
?
setDomain(String pattern)
— Specifies the domain within which this cookie should be
presented
?
setMaxAge(int expiry)
— Sets the maximum age of the cookie in seconds
?
setPath(String uri)
- Specifies a path for the cookie to which the client should return the
cookie
?
setSecure(boolean flag)
— Indicates to the browser whether the cookie should only be
sent using a secure protocol, such as HTTPS or SSL
?
setValue(String newValue)
— Assigns a new value to a cookie after the cookie is created
?
setVersion(int v)
— Sets the version of the cookie protocol this cookie complies with
To get a specific cookie, it’s also necessary to create a function to iterate through each cookie to deter-
mine which one you want:
<%!
public static Cookie getCookie(HttpServletRequest request, String name) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
485
Client-Server Communication
19_579088 ch16.qxd 3/28/05 11:42 AM Page 485
Free JavaScript Editor
Ajax Editor
©
→