Cookie,Session解惑

    As a proficient Java EE programmer, It’s essential to keep in mind the difference beteween Cookie and Session . In this log , I will show you the essence of them . after reading the log ,you will never consult any renference in your development .Ok,Let’go!

1.What is cookie?

    A cookie is a computer text file sent to a visitor's Web browser (the software used to access the Internet such as Internet Explorer and Firefox) by a Web server (the computer that hosts the Web site) in order to remember certain pieces of information. This can be a convenience for both Web site visitors and operators because it can be used to reduce the amount of time to input and process the same information each time a Web site is used.
Information stored within a cookie can be read only by the Web server that originally sent the cookie, not by other Web servers.

    Are there different kinds of cookies?

    The question is well .Ok,There are two types of cookies.

    Session Cookies(Transient Cookie): These cookies reside on the Web browser and have no expiry date. They expire as soon as the visitor closes the Web browser. Session cookies remember information only for as long as the visitor operates the Web browser in a single "session" (or "sitting"). Session cookies can be used by Web site operators to determine information such as what parts of a Web site are popular, how long people stay on certain sections of a Web site and what browsers people are using.

    Persistent Cookies(Permanent Cookie): These cookies have an expiry date, are stored on a visitor's hard drive and are read by the visitor's browser each time. It is possible for the Web site that created the cookie to extend the expiry date without notice to the visitor. They will remain there until the set date has expired or until the visitor has deleted the file. However, most people do not know how to delete cookies. In addition, the prolonged existence of persistent cookies means they can be used to follow Web browsing behaviour and purchasing habits. In some cases, they can also be used to identify a Web visitor when the persistent cookie data is combined with information from other sources such as databases (for example, matching an IP address with a person's name).

2. What’s Session?

    A session as you probably mean it is a server-side object which stores state. You keep hearing people saying HTTP is a stateless protocol, right? They mean when you load a page, you're finished as far as the web server is concerned. If you reload a page, the new request isn't associated in any way with the previous one. Session Provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user.

    The session persists for a specified time period, across more than one connection or page request from the user. A session usually corresponds to one user, who may visit a site many times. The server can maintain a session in many ways such as using cookies or rewriting URLs. 

    In servlet API, There are three interface and one class, which hava direct connection with Cookie and Session . also in my coding , I have always use following function to complete business process.

Interface HttpSession:

(1). Object getAttribute(String name) // Returns the object bound with the specified name in this session, or null if no object is bound under the name
(2). Enumeration getAttributeNames() // Returns an Enumeration of String objects containing the names of all the objects bound to this session.
(3). void setAttribute(String name, Object value) // Binds an object to this session, using the name specified. If an object of the same name is already bound to the session, the object is replaced. If the value passed in is null, this has the same effect as calling removeAttribute().
(4). void removeAttribute(String name) // Removes the object bound with the specified name from this session. If the session does not have an object bound with the specified name, this method does nothing.
(5). void invalidate() // Invalidates this session then unbinds any objects bound to it.
(6). boolean isNew() // Returns true if the client does not yet know about the session or if the client chooses not to join the session. For example, if the server used only cookie-based sessions, and the client had disabled the use of cookies, then a session would be new on each request.

Interface HttpServletResponse

(1). void addCookie(Cookie cookie) // Adds the specified cookie to the response. This method can be called multiple times to set more than one cookie.
(2). String encodeURL(String url) // Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged. The implementation of this method includes the logic to determine whether the session ID needs to be encoded in the URL. For example, if the browser supports cookies, or session tracking is turned off, URL encoding is unnecessary. For robust session tracking, all URLs emitted by a servlet should be run through this method. Otherwise, URL rewriting cannot be used with browsers which do not support cookies.
(3). String encodeRedirectURL(String url) // Encodes the specified URL for use in the sendRedirect method or, if encoding is not needed, returns the URL unchanged. The implementation of this method includes the logic to determine whether the session ID needs to be encoded in the URL. Because the rules for making this determination can differ from those used to decide whether to encode a normal link, this method is separated from the encodeURL method. All URLs sent to the HttpServletResponse.sendRedirect method should be run through this method. Otherwise, URL rewriting cannot be used with browsers which do not support cookies.

Interface HttpServletRequest

(1). Cookie[] getCookies() // Returns an array containing all of the Cookie objects the client sent with this request. This method returns null if no cookies were sent.
(2). HttpSession getSession(boolean create) // Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session. If create is false and the request has no valid HttpSession, this method returns null. To make sure the session is properly maintained, you must call this method before the response is committed.
(3). boolean isRequestedSessionIdInValid() // Checks whether the requested session ID is still valid. If the client did not specify any session ID, this method returns false.
(4). booleanisRequestedSessionIdFromCookie()//Checkswhetherthe requested session ID came in as a cookie
(5). boolean isRequestedSessionIdFromURL() // Checks whether the requested session ID came in as part of the request URL.

Class Cookie

(1). public void setMaxAge(int expiry) // Sets the maximum age of the cookie in seconds. A positive value indicates that the cookie will expire after that many seconds have passed. Note that the value is the maximum age when the cookie will expire, not the cookie's current age. A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. A zero value causes the cookie to be deleted.
(2). public int getMaxAge() // Returns the maximum age of the cookie, specified in seconds, By default, -1 indicating the cookie will persist until browser shutdown.

Ok, It’s time to show the concrete example . Here is my early code about login with out input user name and password , for it uses the session and cookie technology.

Ok , How kind of feeling? I suppose , reading here, you must have a good command of the Cookie and Session Technology . well , I must go to have a rest .Tired ah!

References:
1. http://en.wikipedia.org/wiki/HTTP_cookie
2. http://www.faqs.org/rfcs/rfc2965.html
3. http://www.faqs.org/rfcs/rfc2616.html
4. http://www.faqs.org/rfcs/rfc2396.html

Note:
RFC 2965 – HTTP State Management Mechanisim
RFC 2616 – Hypertext Transfer Protocol - HTTP/1.1
RFC 2396 – Uniform Resource Identifiers(URI): Generic Syntax

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值