2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
17 package javax.servlet.http;
19 import java.io.Serializable;
20 import java.text.MessageFormat;
21 import java.util.BitSet;
22 import java.util.Locale;
23 import java.util.ResourceBundle;
26 * Creates a cookie, a small amount of information sent by a servlet to a Web
27 * browser, saved by the browser, and later sent back to the server. A cookie's
28 * value can uniquely identify a client, so cookies are commonly used for
31 * A cookie has a name, a single value, and optional attributes such as a
32 * comment, path and domain qualifiers, a maximum age, and a version number.
33 * Some Web browsers have bugs in how they handle the optional attributes, so
34 * use them sparingly to improve the interoperability of your servlets.
36 * The servlet sends cookies to the browser by using the
37 * {@link HttpServletResponse#addCookie} method, which adds fields to HTTP
38 * response headers to send cookies to the browser, one at a time. The browser
39 * is expected to support 20 cookies for each Web server, 300 cookies total, and
40 * may limit cookie size to 4 KB each.
42 * The browser returns cookies to the servlet by adding fields to HTTP request
43 * headers. Cookies can be retrieved from a request by using the
44 * {@link HttpServletRequest#getCookies} method. Several cookies might have the
45 * same name but different path attributes.
47 * Cookies affect the caching of the Web pages that use them. HTTP 1.0 does not
48 * cache pages that use cookies created with this class. This class does not
49 * support the cache control defined with HTTP 1.1.
51 * This class supports both the Version 0 (by Netscape) and Version 1 (by RFC
52 * 2109) cookie specifications. By default, cookies are created using Version 0
53 * to ensure the best interoperability.
55 public class Cookie implements Cloneable, Serializable {
57 private static final CookieNameValidator validation;
60 String prop = System.getProperty("org.apache.tomcat.util.http.ServerCookie.STRICT_NAMING");
62 strictNaming = Boolean.parseBoolean(prop);
64 strictNaming = Boolean.getBoolean("org.apache.catalina.STRICT_SERVLET_COMPLIANCE");
68 validation = new RFC2109Validator();
71 validation = new NetscapeValidator();
75 private static final long serialVersionUID = 1L;
77 private final String name;
80 private int version = 0; // ;Version=1 ... means RFC 2109 style
83 // Attributes encoded in the header's cookie fields.
85 private String comment; // ;Comment=VALUE ... describes cookie's use
86 private String domain; // ;Domain=VALUE ... domain that sees cookie
87 private int maxAge = -1; // ;Max-Age=VALUE ... cookies auto-expire
88 private String path; // ;Path=VALUE ... URLs that see the cookie
89 private boolean secure; // ;Secure ... e.g. use SSL
90 private boolean httpOnly; // Not in cookie specs, but supported by browsers
93 * Constructs a cookie with a specified name and value.
95 * The name must conform to RFC 2109. That means it can contain only ASCII
96 * alphanumeric characters and cannot contain commas, semicolons, or white
97 * space or begin with a $ character. The cookie's name cannot be changed
100 * The value can be anything the server chooses to send. Its value is
101 * probably of interest only to the server. The cookie's value can be
102 * changed after creation with the <code>setValue</code> method.
104 * By default, cookies are created according to the Netscape cookie
105 * specification. The version can be changed with the
106 * <code>setVersion</code> method.
109 * a <code>String</code> specifying the name of the cookie
111 * a <code>String</code> specifying the value of the cookie
112 * @throws IllegalArgumentException
113 * if the cookie name contains illegal characters (for example,
114 * a comma, space, or semicolon) or it is one of the tokens
115 * reserved for use by the cookie protocol
119 public Cookie(String name, String value) {
120 validation.validate(name);
126 * Specifies a comment that describes a cookie's purpose. The comment is
127 * useful if the browser presents the cookie to the user. Comments are not
128 * supported by Netscape Version 0 cookies.
131 * a <code>String</code> specifying the comment to display to the
135 public void setComment(String purpose) {
140 * Returns the comment describing the purpose of this cookie, or
141 * <code>null</code> if the cookie has no comment.
143 * @return a <code>String</code> containing the comment, or
144 * <code>null</code> if none
147 public String getComment() {
152 * Specifies the domain within which this cookie should be presented.
154 * The form of the domain name is specified by RFC 2109. A domain name
155 * begins with a dot (<code>.foo.com</code>) and means that the cookie is
156 * visible to servers in a specified Domain Name System (DNS) zone (for
157 * example, <code>www.foo.com</code>, but not <code>a.b.foo.com</code>). By
158 * default, cookies are only returned to the server that sent them.
161 * a <code>String</code> containing the domain name within which
162 * this cookie is visible; form is according to RFC 2109
165 public void setDomain(String pattern) {
166 domain = pattern.toLowerCase(Locale.ENGLISH); // IE allegedly needs this
170 * Returns the domain name set for this cookie. The form of the domain name
171 * is set by RFC 2109.
173 * @return a <code>String</code> containing the domain name
176 public String getDomain() {
181 * Sets the maximum age of the cookie in seconds.
183 * A positive value indicates that the cookie will expire after that many
184 * seconds have passed. Note that the value is the <i>maximum</i> age when
185 * the cookie will expire, not the cookie's current age.
187 * A negative value means that the cookie is not stored persistently and
188 * will be deleted when the Web browser exits. A zero value causes the
189 * cookie to be deleted.
192 * an integer specifying the maximum age of the cookie in
193 * seconds; if negative, means the cookie is not stored; if zero,
197 public void setMaxAge(int expiry) {
202 * Returns the maximum age of the cookie, specified in seconds, By default,
203 * <code>-1</code> indicating the cookie will persist until browser
206 * @return an integer specifying the maximum age of the cookie in seconds; if
207 * negative, means the cookie persists until browser shutdown
210 public int getMaxAge() {
215 * Specifies a path for the cookie to which the client should return the
218 * The cookie is visible to all the pages in the directory you specify, and
219 * all the pages in that directory's subdirectories. A cookie's path must
220 * include the servlet that set the cookie, for example, <i>/catalog</i>,
221 * which makes the cookie visible to all directories on the server under
224 * Consult RFC 2109 (available on the Internet) for more information on
225 * setting path names for cookies.
228 * a <code>String</code> specifying a path
231 public void setPath(String uri) {
236 * Returns the path on the server to which the browser returns this cookie.
237 * The cookie is visible to all subpaths on the server.
239 * @return a <code>String</code> specifying a path that contains a servlet
240 * name, for example, <i>/catalog</i>
243 public String getPath() {
248 * Indicates to the browser whether the cookie should only be sent using a
249 * secure protocol, such as HTTPS or SSL.
251 * The default value is <code>false</code>.
254 * if <code>true</code>, sends the cookie from the browser to the
255 * server only when using a secure protocol; if
256 * <code>false</code>, sent on any protocol
259 public void setSecure(boolean flag) {
264 * Returns <code>true</code> if the browser is sending cookies only over a
265 * secure protocol, or <code>false</code> if the browser can send cookies
266 * using any protocol.
268 * @return <code>true</code> if the browser uses a secure protocol;
269 * otherwise, <code>true</code>
272 public boolean getSecure() {
277 * Returns the name of the cookie. The name cannot be changed after
280 * @return a <code>String</code> specifying the cookie's name
282 public String getName() {
287 * Assigns a new value to a cookie after the cookie is created. If you use a
288 * binary value, you may want to use BASE64 encoding.
290 * With Version 0 cookies, values should not contain white space, brackets,
291 * parentheses, equals signs, commas, double quotes, slashes, question
292 * marks, at signs, colons, and semicolons. Empty values may not behave the
293 * same way on all browsers.
296 * a <code>String</code> specifying the new value
300 public void setValue(String newValue) {
305 * Returns the value of the cookie.
307 * @return a <code>String</code> containing the cookie's present value
311 public String getValue() {
316 * Returns the version of the protocol this cookie complies with. Version 1
317 * complies with RFC 2109, and version 0 complies with the original cookie
318 * specification drafted by Netscape. Cookies provided by a browser use and
319 * identify the browser's cookie version.
321 * @return 0 if the cookie complies with the original Netscape specification;
322 * 1 if the cookie complies with RFC 2109
325 public int getVersion() {
330 * Sets the version of the cookie protocol this cookie complies with.
331 * Version 0 complies with the original Netscape cookie specification.
332 * Version 1 complies with RFC 2109.
334 * Since RFC 2109 is still somewhat new, consider version 1 as experimental;
335 * do not use it yet on production sites.
338 * 0 if the cookie should comply with the original Netscape
339 * specification; 1 if the cookie should comply with RFC 2109
342 public void setVersion(int v) {
347 * Overrides the standard <code>java.lang.Object.clone</code> method to
348 * return a copy of this cookie.
351 public Object clone() {
353 return super.clone();
354 } catch (CloneNotSupportedException e) {
355 throw new RuntimeException(e.getMessage());
360 * Sets the flag that controls if this cookie will be hidden from scripts on
363 * @param httpOnly The new value of the flag
367 public void setHttpOnly(boolean httpOnly) {
368 this.httpOnly = httpOnly;
372 * Gets the flag that controls if this cookie will be hidden from scripts on
375 * @return <code>true</code> if the cookie is hidden from scripts, else
379 public boolean isHttpOnly() {
385 class CookieNameValidator {
386 private static final String LSTRING_FILE = "javax.servlet.http.LocalStrings";
387 private static final ResourceBundle lStrings = ResourceBundle.getBundle(LSTRING_FILE);
389 protected final BitSet allowed;
391 protected CookieNameValidator(String separators) {
392 allowed = new BitSet(128);
393 allowed.set(0x20, 0x7f); // any CHAR except CTLs or separators
394 for (int i = 0; i < separators.length(); i++) {
395 char ch = separators.charAt(i);
400 void validate(String name) {
401 if (name == null || name.length() == 0) {
402 throw new IllegalArgumentException(lStrings.getString("err.cookie_name_blank"));
404 if (!isToken(name) ||
405 name.equalsIgnoreCase("Comment") ||
406 name.equalsIgnoreCase("Discard") ||
407 name.equalsIgnoreCase("Domain") ||
408 name.equalsIgnoreCase("Expires") ||
409 name.equalsIgnoreCase("Max-Age") ||
410 name.equalsIgnoreCase("Path") ||
411 name.equalsIgnoreCase("Secure") ||
412 name.equalsIgnoreCase("Version") ||
413 name.startsWith("$")) {
414 String errMsg = lStrings.getString("err.cookie_name_is_token");
415 throw new IllegalArgumentException(MessageFormat.format(errMsg, name));
419 private boolean isToken(String possibleToken) {
420 int len = possibleToken.length();
422 for (int i = 0; i < len; i++) {
423 char c = possibleToken.charAt(i);
424 if (!allowed.get(c)) {
432 class NetscapeValidator extends CookieNameValidator {
433 private static final String NETSCAPE_SEPARATORS = ",; ";
435 NetscapeValidator() {
436 super(NETSCAPE_SEPARATORS);
440 class RFC2109Validator extends CookieNameValidator {
441 private static final String RFC2616_SEPARATORS = "()<>@,;:\\\"/[]?={} \t";
444 super(RFC2616_SEPARATORS);
446 // special treatment to allow for FWD_SLASH_IS_SEPARATOR property
448 String prop = System.getProperty("org.apache.tomcat.util.http.ServerCookie.FWD_SLASH_IS_SEPARATOR");
450 allowSlash = !Boolean.parseBoolean(prop);
452 allowSlash = !Boolean.getBoolean("org.apache.catalina.STRICT_SERVLET_COMPLIANCE");