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

Save This Page
Home » glassfish-v2ur2-b04-src » javax » servlet » http » [javadoc | source]