Source Code Cross Referenced for Cookie.java in  » 6.0-JDK-Core » Servlet-API-by-tomcat » javax » servlet » http » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Home
Java Source Code / Java Documentation
1.6.0 JDK Core
2.6.0 JDK Modules
3.6.0 JDK Modules com.sun
4.6.0 JDK Modules com.sun.java
5.6.0 JDK Modules sun
6.6.0 JDK Platform
7.Ajax
8.Apache Harmony Java SE
9.Aspect oriented
10.Authentication Authorization
11.Blogger System
12.Build
13.Byte Code
14.Cache
15.Chart
16.Chat
17.Code Analyzer
18.Collaboration
19.Content Management System
20.Database Client
21.Database DBMS
22.Database JDBC Connection Pool
23.Database ORM
24.Development
25.EJB Server
26.ERP CRM Financial
27.ESB
28.Forum
29.Game
30.GIS
31.Graphic 3D
32.Graphic Library
33.Groupware
34.HTML Parser
35.IDE
36.IDE Eclipse
37.IDE Netbeans
38.Installer
39.Internationalization Localization
40.Inversion of Control
41.Issue Tracking
42.J2EE
43.J2ME
44.JBoss
45.JMS
46.JMX
47.Library
48.Mail Clients
49.Music
50.Net
51.Parser
52.PDF
53.Portal
54.Profiler
55.Project Management
56.Report
57.RSS RDF
58.Rule Engine
59.Science
60.Scripting
61.Search Engine
62.Security
63.Sevlet Container
64.Source Control
65.Swing Library
66.Template Engine
67.Test Coverage
68.Testing
69.UML
70.Web Crawler
71.Web Framework
72.Web Mail
73.Web Server
74.Web Services
75.Web Services apache cxf 2.2.6
76.Web Services AXIS2
77.Wiki Engine
78.Workflow Engines
79.XML
80.XML UI
Java Source Code / Java Documentation » 6.0 JDK Core » Servlet API by tomcat » javax.servlet.http 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001        /*
002         * Copyright 2004 The Apache Software Foundation
003         *
004         * Licensed under the Apache License, Version 2.0 (the "License");
005         * you may not use this file except in compliance with the License.
006         * You may obtain a copy of the License at
007         *
008         *     http://www.apache.org/licenses/LICENSE-2.0
009         *
010         * Unless required by applicable law or agreed to in writing, software
011         * distributed under the License is distributed on an "AS IS" BASIS,
012         * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013         * See the License for the specific language governing permissions and
014         * limitations under the License.
015         */
016        package javax.servlet.http;
017
018        import java.text.MessageFormat;
019        import java.util.ResourceBundle;
020
021        /**
022         *
023         * Creates a cookie, a small amount of information sent by a servlet to 
024         * a Web browser, saved by the browser, and later sent back to the server.
025         * A cookie's value can uniquely 
026         * identify a client, so cookies are commonly used for session management.
027         * 
028         * <p>A cookie has a name, a single value, and optional attributes
029         * such as a comment, path and domain qualifiers, a maximum age, and a
030         * version number. Some Web browsers have bugs in how they handle the 
031         * optional attributes, so use them sparingly to improve the interoperability 
032         * of your servlets.
033         *
034         * <p>The servlet sends cookies to the browser by using the
035         * {@link HttpServletResponse#addCookie} method, which adds
036         * fields to HTTP response headers to send cookies to the 
037         * browser, one at a time. The browser is expected to 
038         * support 20 cookies for each Web server, 300 cookies total, and
039         * may limit cookie size to 4 KB each.
040         * 
041         * <p>The browser returns cookies to the servlet by adding 
042         * fields to HTTP request headers. Cookies can be retrieved
043         * from a request by using the {@link HttpServletRequest#getCookies} method.
044         * Several cookies might have the same name but different path attributes.
045         * 
046         * <p>Cookies affect the caching of the Web pages that use them. 
047         * HTTP 1.0 does not cache pages that use cookies created with
048         * this class. This class does not support the cache control
049         * defined with HTTP 1.1.
050         *
051         * <p>This class supports both the Version 0 (by Netscape) and Version 1 
052         * (by RFC 2109) cookie specifications. By default, cookies are
053         * created using Version 0 to ensure the best interoperability.
054         *
055         *
056         * @author	Various
057         * @version	$Version$
058         *
059         */
060
061        // XXX would implement java.io.Serializable too, but can't do that
062        // so long as sun.servlet.* must run on older JDK 1.02 JVMs which
063        // don't include that support.
064        public class Cookie implements  Cloneable {
065
066            private static final String LSTRING_FILE = "javax.servlet.http.LocalStrings";
067            private static ResourceBundle lStrings = ResourceBundle
068                    .getBundle(LSTRING_FILE);
069
070            //
071            // The value of the cookie itself.
072            //
073
074            private String name; // NAME= ... "$Name" style is reserved
075            private String value; // value of NAME
076
077            //
078            // Attributes encoded in the header's cookie fields.
079            //
080
081            private String comment; // ;Comment=VALUE ... describes cookie's use
082            // ;Discard ... implied by maxAge < 0
083            private String domain; // ;Domain=VALUE ... domain that sees cookie
084            private int maxAge = -1; // ;Max-Age=VALUE ... cookies auto-expire
085            private String path; // ;Path=VALUE ... URLs that see the cookie
086            private boolean secure; // ;Secure ... e.g. use SSL
087            private int version = 0; // ;Version=1 ... means RFC 2109++ style
088
089            /**
090             * Constructs a cookie with a specified name and value.
091             *
092             * <p>The name must conform to RFC 2109. That means it can contain 
093             * only ASCII alphanumeric characters and cannot contain commas, 
094             * semicolons, or white space or begin with a $ character. The cookie's
095             * name cannot be changed after creation.
096             *
097             * <p>The value can be anything the server chooses to send. Its
098             * value is probably of interest only to the server. The cookie's
099             * value can be changed after creation with the
100             * <code>setValue</code> method.
101             *
102             * <p>By default, cookies are created according to the Netscape
103             * cookie specification. The version can be changed with the 
104             * <code>setVersion</code> method.
105             *
106             *
107             * @param name 			a <code>String</code> specifying the name of the cookie
108             *
109             * @param value			a <code>String</code> specifying the value of the cookie
110             *
111             * @throws IllegalArgumentException	if the cookie name contains illegal characters
112             *					(for example, a comma, space, or semicolon)
113             *					or it is one of the tokens reserved for use
114             *					by the cookie protocol
115             * @see #setValue
116             * @see #setVersion
117             *
118             */
119
120            public Cookie(String name, String value) {
121                if (!isToken(name)
122                        || name.equalsIgnoreCase("Comment") // rfc2019
123                        || name.equalsIgnoreCase("Discard") // 2019++
124                        || name.equalsIgnoreCase("Domain")
125                        || name.equalsIgnoreCase("Expires") // (old cookies)
126                        || name.equalsIgnoreCase("Max-Age") // rfc2019
127                        || name.equalsIgnoreCase("Path")
128                        || name.equalsIgnoreCase("Secure")
129                        || name.equalsIgnoreCase("Version")
130                        || name.startsWith("$")) {
131                    String errMsg = lStrings
132                            .getString("err.cookie_name_is_token");
133                    Object[] errArgs = new Object[1];
134                    errArgs[0] = name;
135                    errMsg = MessageFormat.format(errMsg, errArgs);
136                    throw new IllegalArgumentException(errMsg);
137                }
138
139                this .name = name;
140                this .value = value;
141            }
142
143            /**
144             *
145             * Specifies a comment that describes a cookie's purpose.
146             * The comment is useful if the browser presents the cookie 
147             * to the user. Comments
148             * are not supported by Netscape Version 0 cookies.
149             *
150             * @param purpose		a <code>String</code> specifying the comment 
151             *				to display to the user
152             *
153             * @see #getComment
154             *
155             */
156
157            public void setComment(String purpose) {
158                comment = purpose;
159            }
160
161            /**
162             * Returns the comment describing the purpose of this cookie, or
163             * <code>null</code> if the cookie has no comment.
164             *
165             * @return			a <code>String</code> containing the comment,
166             *				or <code>null</code> if none
167             *
168             * @see #setComment
169             *
170             */
171
172            public String getComment() {
173                return comment;
174            }
175
176            /**
177             *
178             * Specifies the domain within which this cookie should be presented.
179             *
180             * <p>The form of the domain name is specified by RFC 2109. A domain
181             * name begins with a dot (<code>.foo.com</code>) and means that
182             * the cookie is visible to servers in a specified Domain Name System
183             * (DNS) zone (for example, <code>www.foo.com</code>, but not 
184             * <code>a.b.foo.com</code>). By default, cookies are only returned
185             * to the server that sent them.
186             *
187             *
188             * @param pattern		a <code>String</code> containing the domain name
189             *				within which this cookie is visible;
190             *				form is according to RFC 2109
191             *
192             * @see #getDomain
193             *
194             */
195
196            public void setDomain(String pattern) {
197                domain = pattern.toLowerCase(); // IE allegedly needs this
198            }
199
200            /**
201             * Returns the domain name set for this cookie. The form of 
202             * the domain name is set by RFC 2109.
203             *
204             * @return			a <code>String</code> containing the domain name
205             *
206             * @see #setDomain
207             *
208             */
209
210            public String getDomain() {
211                return domain;
212            }
213
214            /**
215             * Sets the maximum age of the cookie in seconds.
216             *
217             * <p>A positive value indicates that the cookie will expire
218             * after that many seconds have passed. Note that the value is
219             * the <i>maximum</i> age when the cookie will expire, not the cookie's
220             * current age.
221             *
222             * <p>A negative value means
223             * that the cookie is not stored persistently and will be deleted
224             * when the Web browser exits. A zero value causes the cookie
225             * to be deleted.
226             *
227             * @param expiry		an integer specifying the maximum age of the
228             * 				cookie in seconds; if negative, means
229             *				the cookie is not stored; if zero, deletes
230             *				the cookie
231             *
232             *
233             * @see #getMaxAge
234             *
235             */
236
237            public void setMaxAge(int expiry) {
238                maxAge = expiry;
239            }
240
241            /**
242             * Returns the maximum age of the cookie, specified in seconds,
243             * By default, <code>-1</code> indicating the cookie will persist
244             * until browser shutdown.
245             *
246             *
247             * @return			an integer specifying the maximum age of the
248             *				cookie in seconds; if negative, means
249             *				the cookie persists until browser shutdown
250             *
251             *
252             * @see #setMaxAge
253             *
254             */
255
256            public int getMaxAge() {
257                return maxAge;
258            }
259
260            /**
261             * Specifies a path for the cookie
262             * to which the client should return the cookie.
263             *
264             * <p>The cookie is visible to all the pages in the directory
265             * you specify, and all the pages in that directory's subdirectories. 
266             * A cookie's path must include the servlet that set the cookie,
267             * for example, <i>/catalog</i>, which makes the cookie
268             * visible to all directories on the server under <i>/catalog</i>.
269             *
270             * <p>Consult RFC 2109 (available on the Internet) for more
271             * information on setting path names for cookies.
272             *
273             *
274             * @param uri		a <code>String</code> specifying a path
275             *
276             *
277             * @see #getPath
278             *
279             */
280
281            public void setPath(String uri) {
282                path = uri;
283            }
284
285            /**
286             * Returns the path on the server 
287             * to which the browser returns this cookie. The
288             * cookie is visible to all subpaths on the server.
289             *
290             *
291             * @return		a <code>String</code> specifying a path that contains
292             *			a servlet name, for example, <i>/catalog</i>
293             *
294             * @see #setPath
295             *
296             */
297
298            public String getPath() {
299                return path;
300            }
301
302            /**
303             * Indicates to the browser whether the cookie should only be sent
304             * using a secure protocol, such as HTTPS or SSL.
305             *
306             * <p>The default value is <code>false</code>.
307             *
308             * @param flag	if <code>true</code>, sends the cookie from the browser
309             *			to the server only when using a secure protocol;
310             *			if <code>false</code>, sent on any protocol
311             *
312             * @see #getSecure
313             *
314             */
315
316            public void setSecure(boolean flag) {
317                secure = flag;
318            }
319
320            /**
321             * Returns <code>true</code> if the browser is sending cookies
322             * only over a secure protocol, or <code>false</code> if the
323             * browser can send cookies using any protocol.
324             *
325             * @return		<code>true</code> if the browser uses a secure protocol;
326             * 			 otherwise, <code>true</code>
327             *
328             * @see #setSecure
329             *
330             */
331
332            public boolean getSecure() {
333                return secure;
334            }
335
336            /**
337             * Returns the name of the cookie. The name cannot be changed after
338             * creation.
339             *
340             * @return		a <code>String</code> specifying the cookie's name
341             *
342             */
343
344            public String getName() {
345                return name;
346            }
347
348            /**
349             *
350             * Assigns a new value to a cookie after the cookie is created.
351             * If you use a binary value, you may want to use BASE64 encoding.
352             *
353             * <p>With Version 0 cookies, values should not contain white 
354             * space, brackets, parentheses, equals signs, commas,
355             * double quotes, slashes, question marks, at signs, colons,
356             * and semicolons. Empty values may not behave the same way
357             * on all browsers.
358             *
359             * @param newValue		a <code>String</code> specifying the new value 
360             *
361             *
362             * @see #getValue
363             * @see Cookie
364             *
365             */
366
367            public void setValue(String newValue) {
368                value = newValue;
369            }
370
371            /**
372             * Returns the value of the cookie.
373             *
374             * @return			a <code>String</code> containing the cookie's
375             *				present value
376             *
377             * @see #setValue
378             * @see Cookie
379             *
380             */
381
382            public String getValue() {
383                return value;
384            }
385
386            /**
387             * Returns the version of the protocol this cookie complies 
388             * with. Version 1 complies with RFC 2109, 
389             * and version 0 complies with the original
390             * cookie specification drafted by Netscape. Cookies provided
391             * by a browser use and identify the browser's cookie version.
392             * 
393             *
394             * @return			0 if the cookie complies with the
395             *				original Netscape specification; 1
396             *				if the cookie complies with RFC 2109
397             *
398             * @see #setVersion
399             *
400             */
401
402            public int getVersion() {
403                return version;
404            }
405
406            /**
407             * Sets the version of the cookie protocol this cookie complies
408             * with. Version 0 complies with the original Netscape cookie
409             * specification. Version 1 complies with RFC 2109.
410             *
411             * <p>Since RFC 2109 is still somewhat new, consider
412             * version 1 as experimental; do not use it yet on production sites.
413             *
414             *
415             * @param v			0 if the cookie should comply with 
416             *				the original Netscape specification;
417             *				1 if the cookie should comply with RFC 2109
418             *
419             * @see #getVersion
420             *
421             */
422
423            public void setVersion(int v) {
424                version = v;
425            }
426
427            // Note -- disabled for now to allow full Netscape compatibility
428            // from RFC 2068, token special case characters
429            // 
430            // private static final String tspecials = "()<>@,;:\\\"/[]?={} \t";
431
432            private static final String tspecials = ",; ";
433
434            /*
435             * Tests a string and returns true if the string counts as a 
436             * reserved token in the Java language.
437             * 
438             * @param value		the <code>String</code> to be tested
439             *
440             * @return			<code>true</code> if the <code>String</code> is
441             *				a reserved token; <code>false</code>
442             *				if it is not			
443             */
444
445            private boolean isToken(String value) {
446                int len = value.length();
447
448                for (int i = 0; i < len; i++) {
449                    char c = value.charAt(i);
450
451                    if (c < 0x20 || c >= 0x7f || tspecials.indexOf(c) != -1)
452                        return false;
453                }
454                return true;
455            }
456
457            /**
458             *
459             * Overrides the standard <code>java.lang.Object.clone</code> 
460             * method to return a copy of this cookie.
461             *		
462             *
463             */
464
465            public Object clone() {
466                try {
467                    return super .clone();
468                } catch (CloneNotSupportedException e) {
469                    throw new RuntimeException(e.getMessage());
470                }
471            }
472        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.