1 /* 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 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 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. 16 */ 17 package javax.servlet.http; 18 19 import java.text.MessageFormat; 20 import java.util.ResourceBundle; 21 22 /** 23 * 24 * Creates a cookie, a small amount of information sent by a servlet to 25 * a Web browser, saved by the browser, and later sent back to the server. 26 * A cookie's value can uniquely 27 * identify a client, so cookies are commonly used for session management. 28 * 29 * <p>A cookie has a name, a single value, and optional attributes 30 * such as a comment, path and domain qualifiers, a maximum age, and a 31 * version number. Some Web browsers have bugs in how they handle the 32 * optional attributes, so use them sparingly to improve the interoperability 33 * of your servlets. 34 * 35 * <p>The servlet sends cookies to the browser by using the 36 * {@link HttpServletResponse#addCookie} method, which adds 37 * fields to HTTP response headers to send cookies to the 38 * browser, one at a time. The browser is expected to 39 * support 20 cookies for each Web server, 300 cookies total, and 40 * may limit cookie size to 4 KB each. 41 * 42 * <p>The browser returns cookies to the servlet by adding 43 * fields to HTTP request headers. Cookies can be retrieved 44 * from a request by using the {@link HttpServletRequest#getCookies} method. 45 * Several cookies might have the same name but different path attributes. 46 * 47 * <p>Cookies affect the caching of the Web pages that use them. 48 * HTTP 1.0 does not cache pages that use cookies created with 49 * this class. This class does not support the cache control 50 * defined with HTTP 1.1. 51 * 52 * <p>This class supports both the Version 0 (by Netscape) and Version 1 53 * (by RFC 2109) cookie specifications. By default, cookies are 54 * created using Version 0 to ensure the best interoperability. 55 * 56 * 57 * @author Various 58 * @version $Version$ 59 * 60 */ 61 62 // XXX would implement java.io.Serializable too, but can't do that 63 // so long as sun.servlet.* must run on older JDK 1.02 JVMs which 64 // don't include that support. 65 66 public class Cookie implements Cloneable { 67 68 private static final String LSTRING_FILE = 69 "javax.servlet.http.LocalStrings"; 70 private static ResourceBundle lStrings = 71 ResourceBundle.getBundle(LSTRING_FILE); 72 73 // 74 // The value of the cookie itself. 75 // 76 77 private String name; // NAME= ... "$Name" style is reserved 78 private String value; // value of NAME 79 80 // 81 // Attributes encoded in the header's cookie fields. 82 // 83 84 private String comment; // ;Comment=VALUE ... describes cookie's use 85 // ;Discard ... implied by maxAge < 0 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 int version = 0; // ;Version=1 ... means RFC 2109++ style 91 92 93 94 /** 95 * Constructs a cookie with a specified name and value. 96 * 97 * <p>The name must conform to RFC 2109. That means it can contain 98 * only ASCII alphanumeric characters and cannot contain commas, 99 * semicolons, or white space or begin with a $ character. The cookie's 100 * name cannot be changed after creation. 101 * 102 * <p>The value can be anything the server chooses to send. Its 103 * value is probably of interest only to the server. The cookie's 104 * value can be changed after creation with the 105 * <code>setValue</code> method. 106 * 107 * <p>By default, cookies are created according to the Netscape 108 * cookie specification. The version can be changed with the 109 * <code>setVersion</code> method. 110 * 111 * 112 * @param name a <code>String</code> specifying the name of the cookie 113 * 114 * @param value a <code>String</code> specifying the value of the cookie 115 * 116 * @throws IllegalArgumentException if the cookie name contains illegal characters 117 * (for example, a comma, space, or semicolon) 118 * or it is one of the tokens reserved for use 119 * by the cookie protocol 120 * @see #setValue 121 * @see #setVersion 122 * 123 */ 124 125 public Cookie(String name, String value) { 126 if (!isToken(name) 127 || name.equalsIgnoreCase("Comment") // rfc2019 128 || name.equalsIgnoreCase("Discard") // 2019++ 129 || name.equalsIgnoreCase("Domain") 130 || name.equalsIgnoreCase("Expires") // (old cookies) 131 || name.equalsIgnoreCase("Max-Age") // rfc2019 132 || name.equalsIgnoreCase("Path") 133 || name.equalsIgnoreCase("Secure") 134 || name.equalsIgnoreCase("Version") 135 || name.startsWith("$") 136 ) { 137 String errMsg = lStrings.getString("err.cookie_name_is_token"); 138 Object[] errArgs = new Object[1]; 139 errArgs[0] = name; 140 errMsg = MessageFormat.format(errMsg, errArgs); 141 throw new IllegalArgumentException(errMsg); 142 } 143 144 this.name = name; 145 this.value = value; 146 } 147 148 149 150 151 152 /** 153 * 154 * Specifies a comment that describes a cookie's purpose. 155 * The comment is useful if the browser presents the cookie 156 * to the user. Comments 157 * are not supported by Netscape Version 0 cookies. 158 * 159 * @param purpose a <code>String</code> specifying the comment 160 * to display to the user 161 * 162 * @see #getComment 163 * 164 */ 165 166 public void setComment(String purpose) { 167 comment = purpose; 168 } 169 170 171 172 173 /** 174 * Returns the comment describing the purpose of this cookie, or 175 * <code>null</code> if the cookie has no comment. 176 * 177 * @return a <code>String</code> containing the comment, 178 * or <code>null</code> if none 179 * 180 * @see #setComment 181 * 182 */ 183 184 public String getComment() { 185 return comment; 186 } 187 188 189 190 191 192 /** 193 * 194 * Specifies the domain within which this cookie should be presented. 195 * 196 * <p>The form of the domain name is specified by RFC 2109. A domain 197 * name begins with a dot (<code>.foo.com</code>) and means that 198 * the cookie is visible to servers in a specified Domain Name System 199 * (DNS) zone (for example, <code>www.foo.com</code>, but not 200 * <code>a.b.foo.com</code>). By default, cookies are only returned 201 * to the server that sent them. 202 * 203 * 204 * @param pattern a <code>String</code> containing the domain name 205 * within which this cookie is visible; 206 * form is according to RFC 2109 207 * 208 * @see #getDomain 209 * 210 */ 211 212 public void setDomain(String pattern) { 213 domain = pattern.toLowerCase(); // IE allegedly needs this 214 } 215 216 217 218 219 220 /** 221 * Returns the domain name set for this cookie. The form of 222 * the domain name is set by RFC 2109. 223 * 224 * @return a <code>String</code> containing the domain name 225 * 226 * @see #setDomain 227 * 228 */ 229 230 public String getDomain() { 231 return domain; 232 } 233 234 235 236 237 /** 238 * Sets the maximum age of the cookie in seconds. 239 * 240 * <p>A positive value indicates that the cookie will expire 241 * after that many seconds have passed. Note that the value is 242 * the <i>maximum</i> age when the cookie will expire, not the cookie's 243 * current age. 244 * 245 * <p>A negative value means 246 * that the cookie is not stored persistently and will be deleted 247 * when the Web browser exits. A zero value causes the cookie 248 * to be deleted. 249 * 250 * @param expiry an integer specifying the maximum age of the 251 * cookie in seconds; if negative, means 252 * the cookie is not stored; if zero, deletes 253 * the cookie 254 * 255 * 256 * @see #getMaxAge 257 * 258 */ 259 260 public void setMaxAge(int expiry) { 261 maxAge = expiry; 262 } 263 264 265 266 267 /** 268 * Returns the maximum age of the cookie, specified in seconds, 269 * By default, <code>-1</code> indicating the cookie will persist 270 * until browser shutdown. 271 * 272 * 273 * @return an integer specifying the maximum age of the 274 * cookie in seconds; if negative, means 275 * the cookie persists until browser shutdown 276 * 277 * 278 * @see #setMaxAge 279 * 280 */ 281 282 public int getMaxAge() { 283 return maxAge; 284 } 285 286 287 288 289 /** 290 * Specifies a path for the cookie 291 * to which the client should return the cookie. 292 * 293 * <p>The cookie is visible to all the pages in the directory 294 * you specify, and all the pages in that directory's subdirectories. 295 * A cookie's path must include the servlet that set the cookie, 296 * for example, <i>/catalog</i>, which makes the cookie 297 * visible to all directories on the server under <i>/catalog</i>. 298 * 299 * <p>Consult RFC 2109 (available on the Internet) for more 300 * information on setting path names for cookies. 301 * 302 * 303 * @param uri a <code>String</code> specifying a path 304 * 305 * 306 * @see #getPath 307 * 308 */ 309 310 public void setPath(String uri) { 311 path = uri; 312 } 313 314 315 316 317 /** 318 * Returns the path on the server 319 * to which the browser returns this cookie. The 320 * cookie is visible to all subpaths on the server. 321 * 322 * 323 * @return a <code>String</code> specifying a path that contains 324 * a servlet name, for example, <i>/catalog</i> 325 * 326 * @see #setPath 327 * 328 */ 329 330 public String getPath() { 331 return path; 332 } 333 334 335 336 337 338 /** 339 * Indicates to the browser whether the cookie should only be sent 340 * using a secure protocol, such as HTTPS or SSL. 341 * 342 * <p>The default value is <code>false</code>. 343 * 344 * @param flag if <code>true</code>, sends the cookie from the browser 345 * to the server only when using a secure protocol; 346 * if <code>false</code>, sent on any protocol 347 * 348 * @see #getSecure 349 * 350 */ 351 352 public void setSecure(boolean flag) { 353 secure = flag; 354 } 355 356 357 358 359 /** 360 * Returns <code>true</code> if the browser is sending cookies 361 * only over a secure protocol, or <code>false</code> if the 362 * browser can send cookies using any protocol. 363 * 364 * @return <code>true</code> if the browser uses a secure protocol; 365 * otherwise, <code>true</code> 366 * 367 * @see #setSecure 368 * 369 */ 370 371 public boolean getSecure() { 372 return secure; 373 } 374 375 376 377 378 379 /** 380 * Returns the name of the cookie. The name cannot be changed after 381 * creation. 382 * 383 * @return a <code>String</code> specifying the cookie's name 384 * 385 */ 386 387 public String getName() { 388 return name; 389 } 390 391 392 393 394 395 /** 396 * 397 * Assigns a new value to a cookie after the cookie is created. 398 * If you use a binary value, you may want to use BASE64 encoding. 399 * 400 * <p>With Version 0 cookies, values should not contain white 401 * space, brackets, parentheses, equals signs, commas, 402 * double quotes, slashes, question marks, at signs, colons, 403 * and semicolons. Empty values may not behave the same way 404 * on all browsers. 405 * 406 * @param newValue a <code>String</code> specifying the new value 407 * 408 * 409 * @see #getValue 410 * @see Cookie 411 * 412 */ 413 414 public void setValue(String newValue) { 415 value = newValue; 416 } 417 418 419 420 421 /** 422 * Returns the value of the cookie. 423 * 424 * @return a <code>String</code> containing the cookie's 425 * present value 426 * 427 * @see #setValue 428 * @see Cookie 429 * 430 */ 431 432 public String getValue() { 433 return value; 434 } 435 436 437 438 439 /** 440 * Returns the version of the protocol this cookie complies 441 * with. Version 1 complies with RFC 2109, 442 * and version 0 complies with the original 443 * cookie specification drafted by Netscape. Cookies provided 444 * by a browser use and identify the browser's cookie version. 445 * 446 * 447 * @return 0 if the cookie complies with the 448 * original Netscape specification; 1 449 * if the cookie complies with RFC 2109 450 * 451 * @see #setVersion 452 * 453 */ 454 455 public int getVersion() { 456 return version; 457 } 458 459 460 461 462 /** 463 * Sets the version of the cookie protocol this cookie complies 464 * with. Version 0 complies with the original Netscape cookie 465 * specification. Version 1 complies with RFC 2109. 466 * 467 * <p>Since RFC 2109 is still somewhat new, consider 468 * version 1 as experimental; do not use it yet on production sites. 469 * 470 * 471 * @param v 0 if the cookie should comply with 472 * the original Netscape specification; 473 * 1 if the cookie should comply with RFC 2109 474 * 475 * @see #getVersion 476 * 477 */ 478 479 public void setVersion(int v) { 480 version = v; 481 } 482 483 // Note -- disabled for now to allow full Netscape compatibility 484 // from RFC 2068, token special case characters 485 // 486 // private static final String tspecials = "()<>@,;:\\\"/[]?={} \t"; 487 488 private static final String tspecials = ",; "; 489 490 491 492 493 /* 494 * Tests a string and returns true if the string counts as a 495 * reserved token in the Java language. 496 * 497 * @param value the <code>String</code> to be tested 498 * 499 * @return <code>true</code> if the <code>String</code> is 500 * a reserved token; <code>false</code> 501 * if it is not 502 */ 503 504 private boolean isToken(String value) { 505 int len = value.length(); 506 507 for (int i = 0; i < len; i++) { 508 char c = value.charAt(i); 509 510 if (c < 0x20 || c >= 0x7f || tspecials.indexOf(c) != -1) 511 return false; 512 } 513 return true; 514 } 515 516 517 518 519 520 521 /** 522 * 523 * Overrides the standard <code>java.lang.Object.clone</code> 524 * method to return a copy of this cookie. 525 * 526 * 527 */ 528 529 public Object clone() { 530 try { 531 return super.clone(); 532 } catch (CloneNotSupportedException e) { 533 throw new RuntimeException(e.getMessage()); 534 } 535 } 536 } 537