Java EE Learning Note servlet/jsp (3)

Source: Internet
Author: User
Tags session id

Session and Cookie Introduction

1.session concept

Although the session mechanism has been used in Web applications for a long time, there are still a lot of people who do not know the nature of the session mechanism, and today we come to understand.

Session, Chinese is often translated into a conversation, its original meaning refers to the beginning and end of a series of actions/messages, such as the phone from the pick up the phone to dial to hang up the phone in the middle of a series of processes can be called a session. Sometimes we can see the words "during a browser session, ...", where the term "session" is used in its original meaning, which means opening from a browser window to closing this period. The semantics of session in the context of web development refers to a class of solutions for maintaining state between client and server. in the context of a particular language, the session is also used to refer to the solution of the language, such as the javax.servlet.http.HttpSession that are often referred to in Java as a session.

2.HTTP protocol and status hold

The HTTP protocol itself is stateless, which is consistent with the HTTP protocol's original purpose, the client simply needs to request to the server to download some files, both the client and the server do not need to record each other's past behavior, each request is independent, Like the relationship between a customer and a vending machine or an ordinary (non-membership) hypermarket.

Let's use a few examples to describe the difference and connection between a cookie and a session mechanism. I used to go to a coffee shop to drink 5 cups of coffee free of charge for a cup of coffee, but a one-time consumption of 5 cups of coffee is very little, then need some way to record a customer's consumption quantity. Imagine the fact that there are several options below:

A, the shop clerk is very strong, can remember each customer's consumption quantity, as long as the customer walked into the coffee shop, the clerk knew how to treat. This approach is the protocol itself that supports the state.

b, a card issued to customers, the above record the amount of consumption, there is generally a valid period. If the customer presents this card each time it is consumed, the consumption will be linked to the previous or subsequent consumption. This practice is to keep the state on the client.

C, issued to the customer a membership card, in addition to the card number of what information is not recorded, each time the consumer, if the customer presented the card, the shop clerk in the store records found this card number corresponding record add some consumer information. This is done by keeping the state on the server side.

Since the HTTP protocol is stateless and does not want to be stateful due to various considerations, the next two scenarios become a realistic choice. In particular, the cookie mechanism uses a scheme that maintains state on the client, while the session mechanism uses a scenario that maintains state on the server side. We also see that the session mechanism may need to use a cookie mechanism to save the identity, but in fact it has other options because the server-side hold-state scheme also needs to preserve an identity on the client side.

3.cookie mechanism

The rationale for the cookie mechanism is as simple as the example above, but there are several issues to be solved: how to distribute the membership card, the content of the membership card, and how the customer uses the loyalty card.

Orthodox cookie distribution is implemented by extending the HTTP protocol, and the server prompts the browser to generate the appropriate cookie by adding a special line of instructions to the HTTP response header. However, purely client-side scripts such as JavaScript or VBScript can also generate cookies.

And the use of cookies by the browser in accordance with certain principles in the background automatically sent to the server. The browser checks all stored cookies and, if a cookie declares a scope greater than or equal to the location of the resource to be requested, sends the cookie to the server on the HTTP request header of the requesting resource. McDonald's membership card can only be presented in the McDonald's store, if a branch also issued their own membership card, then into the store in addition to show McDonald's membership card, but also to show the store's membership card.

If you do not set an expiration time, the cookie will not be in the lifetime of the browser session, as long as the browser window is closed. This cookie, which is the lifetime of the browser session, is referred to as a session cookie. Session cookies are generally not stored on the hard disk but are kept in memory, although this behavior is not regulated. If the expiration time is set, the browser will save the cookie to the hard disk, turn it off and open the browser again, and the cookies remain valid until the set expiration time expires.

Cookies stored on the hard disk can be shared between different browser processes, such as two IE windows. For cookies stored in memory, different browsers have different ways of handling them.

Here is an example of a goolge setting a cookie's response header
http/1.1 302 Found
location:http://www.google.com/intl/zh-cn/
set-cookie:pref=id=0565f77e132de138:nw=1:tm=1098082649:lm=1098082649:
S=kaeacfpo49ria_d8; Expires=sun, 17-jan-2038 19:14:07 GMT; path=/; Domain=.google.com
Content-type:text/html

4.session mechanism

The session mechanism is a server-side mechanism. When a program needs to create a session for a client's request, the server first checks to see if a session ID is included in the client's request-called the session ID. If it contains a session The ID indicates that the session was previously created for this client, and the server retrieves the session using the session ID (if it is not retrieved, it may create a new one) if the client request does not include the session ID. Creates a session for this client and generates a session Id,session ID value associated with this session should be a string that is neither duplicated nor easily found to mimic the pattern, this session The ID will be returned to the client in this response to be saved.

This session ID can be saved by using a cookie, so that the browser can automatically play the logo to the server during the interactive process. The key value is Jsessionid.

Since cookies can be artificially banned, there must be other mechanisms that can still pass the session ID back to the server when the cookie is banned. a technique that is often used is called URL rewriting, which attaches the session ID directly behind the URL path, and there are two additional ways:

一种是作为URL路径的附加信息,表现形式为http://...../xxx;jsessionid= ByOK3vjFD75aPnrF7C2HmdnV6QZcEbzWoWiBYEnLerjQ99zWpBng!-145788764另一种是作为查询字符串附加在URL后面,表现形式为http://...../xxx?jsessionid=ByOK3vjFD75aPnrF7C2HmdnV6QZcEbzWoWiBYEnLerjQ99zWpBng!-145788764

These two ways for the user is no difference, but the server in the resolution of the way the process is different, the first way is also conducive to the session ID information and normal program parameters separated.
In order to maintain state throughout the interaction, the session ID must be included after each client may request a path.

Another technique is called a form-hidden field. Is that the server automatically modifies the form, adding a hidden field so that the session ID can be passed back to the server when the form is submitted. such as the following form

<form name="testform" action="/xxx"><input type="text"></form>

will be rewritten before being passed to the client.

<form name="testform" action="/xxx"type="hidden" name="jsessionid"value="ByOK3vjFD75aPnrF7C2HmdnV6QZcEbzWoWiBYEnLerjQ99zWpBng!-145788764"type="text"></form>

This technique is now less applied, and the very old IPlanet6 (the predecessor of the SunOne Application server) that the author has contacted has used this technique.
In fact, this technique can be replaced simply by applying URL rewriting to the action.

Attention:

HttpSession 存在于一次请求中,只要地址栏发生了改变就算发出了请求了。但是内部跳转算一次请求,因为它的地址栏不会发生改变。提交表单属于一次请求,因为地址栏发生了改变。

5.HttpSession FAQs

When is the problem 1:session created?

A common misconception is that the session is created when there is client access, but the fact is that it is not created until a statement such as Httpservletrequest.getsession (true) is called by a server-side program, and note that if the JSP does not display the use <% @page session= "false"%> the session is closed, the JSP file is automatically translated into a servlet with such a statement HttpSession session = Httpservletrequest.getsession (true); This is also the origin of the hidden session object in JSP.

Question 2:session when it was deleted

Often heard a misunderstanding "as long as the browser is closed, the session disappears." In fact, you can imagine the membership card example, unless the customer actively to the store to sell cards, otherwise the store will not easily delete customer information. For the session is the same, unless the program notifies the server to delete a session, or the server will remain, the program is generally in the user to log off when sending an instruction to delete the session. However, the browser will never proactively notify the server before shutting down, so the server will not have the opportunity to know that the browser has been shut down, the reason for this illusion is that most sessions use session cookies to save the conversation ID, and after closing the browser this The session ID disappears and the original session cannot be found when connecting to the server again. If the cookie set by the server is saved to the hard disk, or if a device is used to overwrite the HTTP request header sent by the browser, and the original session ID is sent to the server, the original session can still be found by opening the browser again.

Session is deleted under the following circumstances

a.程序调用HttpSession.invalidate();b.距离上一次收到客户端发送的session id时间间隔超过了session的超时设置;c.服务器进程被停止(非持久session)

Attention:

Question 3: How do I delete a session when the browser is closed

Strictly speaking, do not do this. One way to do this is to use JavaScript code window.oncolose on all client pages to monitor the browser's closing action, and then send a request to the server to delete the session. But there is still nothing to do with the unconventional means of a browser crash or a forced kill process.

Question 4: How to properly cope with the possibility of a client prohibiting cookies

Use URL overrides for all URLs, including hyperlinks, action for form, and redirected URLs. This is because the address bar changes when you jump, sending a new request. You will create a sesssion.

Question 5: Must the object stored in the session be serializable?

are not required. Requires that the object be serializable only for the session to be replicated in the cluster or to be persisted or, if necessary, the server can swap the session out of memory temporarily. Placing a non-serializable object in the session of the Weblogic server will receive a warning on the console.

Issue 6: Open two browser windows access the application will use the same session or a different session

If you want to determine whether the same session, just to determine whether the client sends to the server Jsessionid is the same, and Jsessionid is stored in the client's cookie (ie, browser), so you have to see the use of the cookie is the default or set the expiration time. (Because the location of the cookie is different in either way)

如果是默认的,换了浏览器就没有cookie了,因为默认的cookie是保存在浏览器上的(即内存中)。如果是设置了过期时间的,在没过期的时间内,换浏览器是可以共享cookie的,前提是使用的缓存目录是相同的,因为设置了过期时间的cookie是保存在硬盘上的。

Java EE Learning Note servlet/jsp (3)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.