Session lifecycle

Source: Internet
Author: User
Session Lifecycle 2 (13:46:22) Reprinted token
Tags: Miscellaneous  
Session lifecycle

The Session is stored on the server. In order to get a higher access speed, the server generally places the Session in the memory. Each user has an independent Session. If the Session content is too complex, memory overflow may occur when a large number of customers access the server. Therefore, the information in the Session should be simplified as much as possible.

The Session is automatically created when the user first accesses the server. You must note that the Session will be created only when you access JSP, Servlet, and other programs. The Session will not be created only when you access static resources such as HTML and IMAGE. If the Session has not been generated, you can also use request. getSession (true) to force the Session generation.

After a Session is generated, the server updates the last access time of the Session and maintains the Session. Each time a user accesses the server, whether or not the Session is read or written, the server considers the user's Session "active" once.

 


As more and more users access the server, the number of sessions increases. To prevent memory overflow, the server deletes sessions that are not active for a long time from the memory. This is the Session timeout time. If the server has not been accessed after the timeout, the Session will automatically fail.

The timeout value of the Session is the maxInactiveInterval attribute. You can obtain the timeout value through getMaxInactiveInterval () and modify it through setMaxInactiveInterval (long interval.

The Session timeout can also be modified in web. xml. In addition, the Session can be invalidated by calling the invalidate () method of the Session.


Sessions include various methods, which are much easier to use than cookies. Common methods of Session are shown in Table 5.2.

Table 5.2 common methods of HttpSession

Method name
Description

Void setAttribute (String attribute, Object value) sets the Session attribute. The value parameter can be any Java Object. It is generally a Java Bean.

The value information should not be too large.

String getAttribute (String attribute) returns the Session attribute.

Enumeration getAttributeNames () returns the attribute name in the Session.

Void removeAttribute (String attribute) remove Session attributes

String getId () returns the Session ID. This ID is automatically created by the server and will not be repeated.

Long getCreationTime () returns the date on which the Session was created. The return type is long and is often converted to the Date type. For example:

Date createTime = new Date (session. getCreationTime ())

Long getLastAccessedTime () returns the last active time of the Session. The return type is long.

Int getMaxInactiveInterval () returns the Session timeout. The unit is seconds. If no access is made after this time, the server considers the Session invalid.

Void setMaxInactiveInterval (int second) sets the Session timeout time. Unit: Seconds

Void putValue (String attribute, Object value)
This method is not recommended. Already replaced by setAttribute (String attribute, Object Value)

Object getValue (String attribute) is not recommended. It has been replaced by getAttribute (String attr)

Boolean isNew () returns whether the Session is newly created.

Void invalidate () invalidates the Session


The default timeout value of Session in Tomcat is 20 minutes. Use setMaxInactiveInterval (int seconds) to modify the timeout value. You can modify web. xml to change the default Session timeout. For example, to 60 minutes:

<Session-config>
<Session-timeout> 60 </session-timeout> <! -- Unit: minute -->
</Session-config>
Note: The unit of the <session-timeout> parameter is minute, while that of setMaxInactiveInterval (int s) is second.

 

Browser requirements of Session

Although the Session is stored on the server and transparent to the client, its normal operation still requires support from the client browser. This is because the Session needs to use cookies as the identification mark. The HTTP protocol is stateless, and the Session cannot determine whether it is the same customer based on the HTTP connection. Therefore, the server sends a Cookie named JSESSIONID to the client browser, the value is the Session id (HttpSession. return value of getId ). The Session identifies whether the Session is the same user based on the Cookie.

The Cookie is automatically generated by the server. Its maxAge attribute is generally-1, indicating that the Cookie is valid only in the current browser and is not shared among various browser windows. If you close the browser, it will become invalid. Therefore, when two browser windows of the same machine access the server, two different sessions are generated. Except for new windows opened by links and scripts in the browser window (that is, windows opened by double-clicking the desktop browser icon. This type of child window will share the Cookie of the parent window, so it will share a Session.

Note: New sessions are generated in the new browser window, except for subwindows. The child window shares the Session of the parent window. For example, if you right-click the link and select "open in new window" in the shortcut menu, the child window can access the Session in the parent window.

What if the client browser disables or does not support cookies? For example, most mobile browsers do not support cookies. Java Web provides another solution: URL address rewriting.

 

URL address rewriting

URL address rewriting is a solution that does not support cookies on the client. The URL address rewriting principle is to overwrite the Session id information of the user to the URL address. The server can parse the rewritten URL to obtain the Session id. In this way, you can use Session to record user status even if the client does not support cookies. The HttpServletResponse class provides encodeURL (String url) for URL address rewriting. For example:

<Td> <a href = "<% = response. encodeURL (" index. jsp? C = 1 & wd = Java ") %>"> Homepage </a> </td> this method automatically determines whether the client supports cookies. If the client supports cookies, the URLs will be output in an intact manner. If the client does not support cookies, the user Session id is rewritten to the URL. The output after rewriting may be like this:

<Td> <a href = "index. jsp; jsessionid = 0CCD096E7F8D97B0BE608AFDC3E1931E? C = 1 & wd = Java "> Homepage </a> </td> after the file name, the string"; jsessionid = XXX "is added before the URL parameter ". XXX indicates the Session id. The added jsessionid string does not affect the requested file name or the submitted address bar parameters. When you click this link, the Session id is submitted to the server through the URL, and the server obtains the Session id by parsing the URL address.

For Redirection, you can rewrite the URL address as follows:

<% If ("administrator ". equals (userName) {response. sendRedirect (response. encodeRedirectURL ("administrator. jsp "); return ;}%> effect and response. the encodeURL (String url) is the same: if the client supports cookies, the original URL address is generated. If the Cookie is not supported, the rewritten address with the jsessionid String is returned.

For WAP programs, because most mobile browsers do not support cookies, WAP programs use URL address rewriting to track user sessions. For example, Yonyou Group's mobile business street.

Note: TOMCAT determines whether the client browser supports cookies based on whether the request contains cookies. Although the client may support cookies, since the first request does not carry any cookies (because no cookies can be carried), the URL address after rewriting will still contain the jsessionid. When the second access is performed, the server has already written cookies in the browser. Therefore, the URL address after rewriting does not contain the jsessionid.


Disable Cookie in Session

Since most of the client browsers on WAP do not support cookies, it is better to simply prohibit Session from using cookies and rewrite URLs in a unified manner. Java Web norms support disabling cookies through configuration. The following example shows how to disable the use of cookies through configuration.

Open the META-INF folder under the WebRoot Directory of the project sessionWeb (same as the WEB-INF folder, created if no), Open context. xml (created if no), and edit the content as follows:

Code 5.11/META-INF/context. xml

<? Xml version = '1. 0' encoding = 'utf-8'?> <Context path = "/sessionWeb" cookies = "false"> </Context> or modify the conf/context. xml file in Tomcat as follows:

Code 5.12 context. xml

<! -- The contents of this file will be loadedfor each web application --> <Context cookies = "false"> <! --... After the intermediate code is slightly --> </Context> deployed, TOMCAT will not automatically generate a Cookie named JSESSIONID, and the Session will not identify the Cookie, it only uses the rewritten URL address as the identification mark.

Note: This configuration only disables the Session from using cookies as identification marks and does not prevent other cookies from being read/written. That is to say, the server will not automatically maintain the Cookie named JSESSIONID, but other cookies can still be read and written in the program.


Session and Cookie comparison

Cookie and Session can be tracked, but the implementation principle is not the same. In general, both of them can meet the requirements, but sometimes they cannot use cookies or sessions. The following compares the characteristics of the two and their applicability.

5.3.1 comparison of access methods

Cookie can only save ASCII string, if you need to access Unicode characters or binary data, need to UTF-8, GBK or BASE64 encoding. Java objects cannot be directly accessed in cookies. It is difficult to use cookies to store slightly complex information.

The Session can access any type of data, including, but not limited to, String, Integer, List, and Map. The Session can also directly save Java Beans and any Java classes and objects, which is very convenient to use. Session can be viewed as a Java container class.

Privacy Security comparison

The Cookie is stored in the client browser and visible to the client. Some client programs may snoop, copy, or even modify the content in the Cookie. Sessions are stored on servers and transparent to clients, so there is no risk of sensitive information leakage.

If you use cookies, we recommend that you do not write sensitive information, such as your account and password, into cookies. It is best to encrypt the Cookie information like Google and Baidu, submit it to the server, and decrypt it again to ensure that the information in the Cookie can only be read by itself. If you select a Session, it will save you a lot of trouble. It will be placed on the server, and any privacy in the Session will be fine.


Comparison of validity period

Anyone who has used Google knows that if they have logged on to Google, Google's logon message remains valid for a long time. Users do not have to log on again every time they access the website. Google will record the logon information of the user for a long time. To achieve this, using cookies is a good choice. You only need to set the maxAge attribute of Cookie to a large number or Integer. MAX_VALUE. The maxAge attribute of Cookie supports this effect.

This effect can also be achieved theoretically using Session. You only need to call the setMaxInactiveInterval (Integer. MAX_VALUE) method. However, because the Session depends on the Cookie named JSESSIONID, and the maxAge of the Cookie JSESSIONID is-1 by default, the Session becomes invalid if the browser is closed, so the Session cannot be permanently effective. URL address rewriting cannot be implemented either.

In addition, if the set Session timeout time is too long, the more sessions the server accumulates, the more likely it will cause memory overflow.


Compare the load on the server

A Session is stored on the server. Each user generates a Session. If a large number of concurrent users are accessed, a large number of sessions are generated, consuming a large amount of memory. Therefore, websites with high concurrent access volumes such as Google, Baidu, and Sina are unlikely to use sessions to track customer sessions.

The Cookie is stored on the client and does not occupy server resources. If a large number of users are browsed concurrently, cookies are a good choice. Cookie may be the only choice for Google, Baidu, and Sina.

 

Comparison on browser support

Cookie is supported by the client browser. If the client disables or does not support cookies, session tracking will become invalid. For WAP applications, regular cookies are useless.

If the client browser does not support cookies, you need to use Session and URL address rewriting. Note that response must be used for all URLs that use the Session program. encodeURL (String URL) or response. encodeRedirectURL (String URL) is used to rewrite the URL address. Otherwise, Session tracing fails. For WAP applications, rewriting of Session + URL addresses may be the only option.

If the client supports cookies, the Cookie can be set as valid in the browser window and subwindow (set maxAge to-1 ), it can also be set to valid in all browser windows (set maxAge to an integer greater than 0 ). However, the Session can only be valid in the current browser window and its subwindows. If the two browser windows are irrelevant, they use two different sessions.


Cross-domain comparison

Cookie supports cross-domain access. For example, if the domain attribute is set to ".helloweenvsfei.com", all domain names suffixed with ".helloweenvsfei.com" can access the Cookie. Cross-domain Cookie is now widely used in networks, such as Google, Baidu, and Sina. Session does not support cross-domain access. The Session is only valid within the domain name.

Note: Using cookies only or using Session alone may not achieve the desired effect. In this case, try using both Cookie and Session. The combination of cookies and sessions will achieve brilliant results in actual projects.


Summary of this Chapter

Cookie is an early session tracking technology that saves information to the client browser. When a browser accesses a website, it carries the Cookie information to identify the website.

Session is a Session tracking technology established on the basis of cookies. It stores information on the server side, and the Session can store responsible Java objects, making it easier to use. The Session depends on the Cookie named JSESSIONID.

If the client browser does not support cookies or disables cookies, you can still use the Session by rewriting the URL address.

Link: http://blog.sina.com.cn/s/blog_72c8c1150100qpgl.html

Session lifecycle

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.