ASP Lecture Series (19) Managing Sessions
Author:Eve Cole
Update Time:2009-05-30 19:58:38
One of the challenges of successfully developing Web applications is maintaining user information while the user jumps from page to page in an application during a user visit, or session. HTTP is a stateless protocol, which means that the Web server treats each access to a page as an unrelated access; the server does not retain any information about the previous access, even if the access occurs within a few days of the current access. seconds ago. This lack of memory of previous visits makes it difficult to write applications such as online catalogs, which may need to keep track of catalog items that a user has selected while jumping between different pages of the catalog.
ASP provides a unique solution for managing session information issues. Using the ASP Session object and a special user ID generated by your server, you can create an intelligent application that can identify each incoming user and collect information used by the application to track the user's preferences or content selections. .
ASP sets the user ID through HTTP cookies. HTTP cookies are small files stored on the user's browser. Therefore, if you are creating an application for a browser that does not support cookies, or if your clients have set their browsers not to accept cookies, do not use ASP's session management functionality.
You can also write scripts that run when the application starts or ends.
Starting and Ending Sessions Sessions can be started in three ways:
A new user requests access to a URL that identifies an .asp file in an application whose Global.asa file contains the Session_OnStart procedure.
The user stores a value in the Session object.
The user requests an application's .asp file, and the application's Global.asa file uses the <OBJECT> tag to create an instance of the object with session scope.
If the user does not request or refresh any page in the application for a specified period of time, the session will automatically end. The default value for this period is 20 minutes. You can change the application's default timeout limit setting by setting the "Session Timeout" property in the "Application Options" property page in Internet Services Manager. This value should be set based on the requirements of your web application and the memory space of the server. For example, if you want users browsing your Web application to stay on each page for only a few minutes, you should shorten the default session timeout value. A session timeout value that is too long will cause too many open sessions to exhaust your server's memory resources.
For a specific session, if you want to set a timeout value that is less than the default timeout value, you can set the Timeout property of the Session object. For example, the following script sets the timeout value to 5 minutes.
<%Session.Timeout = 5%>
You can also set a timeout value greater than the default setting. The Session.Timeout property determines the timeout value.
You can also explicitly end a session through the Session object's Abandon method. For example, to provide an Exit button in a table, set the button's ACTION parameter to the URL of an .asp file that contains the following command.
<% Session.Abandon %>
About SessionID and Cookies
When a user first requests an .asp file in a given application, ASP generates a SessionID. SessionID is a number generated by a complex algorithm that uniquely identifies each user session. At the beginning of a new session, the server stores the Session ID as a cookie in the user's Web browser.
A SessionID is much like a key in that ASP can store user information in a "safe" on the server when the user interacts with the application during a session. Just as a key can be used to access items in a safe, the contents of the "safe" can be accessed through the user's SessionID cookie sent in the HTTP request header. Whenever ASP receives a page request, it checks the HTTP request header to obtain the SessionID cookie.
After the SessionID cookie is stored in the user's browser, ASP still reuses the cookie to track the session even if the user requests another .asp file, or requests an .asp file running in another application. Similarly, if the user intentionally abandons the session or lets the session time out, and then requests another .asp file, ASP will start a new session with the same cookie. Only when the server administrator restarts the server or the user restarts the Web browser, the SessionID settings stored in the memory will be cleared and the user will get a new SessionID cookie.
By reusing the SessionID cookie, ASP minimizes the number of cookies sent to the user's browser. Alternatively, if you decide that your ASP application does not require session management, you can prevent ASP from tracking sessions and sending SessionIDs to users.
ASP does not send session cookies under the following circumstances:
The application's session state is disabled.
An ASP page is defined as sessionless, that is, the page contains the <%@ EnableSessionState=False %> tag.
Please note that the SessionID cookie does not provide a permanent method of tracking a user across multiple visits to a Web site. SessionID information stored in server memory can easily be lost. If you want to track users who visit your Web application over time, you must create a user identity by storing a special cookie in the user's Web browser and saving the cookie information in a database.
Store data in Session object
The Session object provides a dynamic associative array in which information can be stored. You can store numeric variables and object variables in Session objects.
Variables can be stored in a Session object by assigning values to named items in the Session object. For example, the following command stores two new variables in the Session object:
<%
Session("FirstName") = "Jeff"
Session("LastName") = "Smith"
%>
Information can be obtained from the Session object by accessing this named item. For example, display the current value of Session("FirstName"):
Welcome <%= Session("FirstName") %>
You can store the user's preferences in the Session object and then access the preferences to decide which page to send to the user. For example, you can allow users to specify a text-only version of content on the first page of your application and apply this selection to all subsequent pages of the application that the user visits.
<% If Session("ScreenResolution") = "Low" Then %>
This is the text version of the page.
<%Else%>
This is the multimedia version of the page.
<% End If %>
You can also store an object instance in the Session object, but doing so will affect server performance.
Manage Web Farm sessions
ASP session information is stored in the Web server. The browser must request a page from the Web server to obtain the script used to access session information. In a Web Farm (where many Web servers share the responsibility of responding to user requests), user requests are not always routed to the same server, but rather to the URL by a special software called a "load balancing" process. The site's application is assigned to any free server. The load balancing process makes it more difficult to preserve session information in Web Farm.
In order to use ASP session management on a load-balanced site, you must ensure that all requests for a user session are directed to the same Web server. One approach is to write a Session_OnStart procedure that uses a Response object to redirect the browser to the Web server running the user's session. If all links in your application pages are relative, then all future requests for a page will be routed to the same server.
For example, a user wants to access an application by requesting a site's universal URL: http://www.microsoft.com. The load balancing process routes requests to server server3.microsoft.com. ASP generated a new user session on this server. During the Session_OnStart process, the browser is redirected to the specified server:
<% Response.Redirect("http://server3.microsoft.com/webapps/firstpage.asp") %>
The browser will request the specified page, and all future requests will be routed to the same server.
Use cookies
A cookie is a token that the web server embeds in the user's web browser to represent the user. The next time the same browser requests a page, it will send the cookie received from the Web server. A cookie allows a set of information to be associated with a user. ASP scripts use the Cookies collection of Response and Request objects to get and set cookie values.
Set cookies
To set the value of a cookie, use Response.Cookies. If the cookie does not exist, Response.Cookies will create a new cookie. For example, to send a cookie name ("planet") with an associated value ("Mars") to the browser, use the following commands, which must appear before the <HTML> tag of your Web page:
<% Response.Cookies("planet")="Mars" %>
If you only want the cookie to be used during the current user session, just send the cookie to the browser. However, if you want to recognize the user after they have terminated or restarted the browser, you must force the browser to store the cookie on the computer's hard drive. To save a cookie, use the Expires property of Response.Cookies and set the date to a day in the future:
<%
Response.Cookies("planet") = "Mars"
Response.Cookies("planet").Expires = "January 1, 1999"
%>
A cookie can have multiple values; such a cookie is called an indexed cookie. Each cookie value is assigned a keyword; you can set the value of a specific cookie keyword. For example:
<% Response.Cookies("planet")("Mars")="SpaceMissions" %>
If an existing cookie has a keyword value but Response.Cookies does not specify the name of a keyword, the keyword value will be deleted. Similarly, if an existing cookie does not have a keyword value but Response.Cookies specifies the name and value of the keyword, the existing cookie value will be deleted and a new key-value pair will be generated.
Get cookies
To obtain the value of a cookie, use the Request.Cookies collection. For example, if the user's HTTP request sets planet=Mars, the following statement will obtain the value Mars:
<%= Request.Cookies("planet") %>
Similarly, to get a keyword value from an indexed cookie, use the keyword name. For example, if the user makes the following HTTP request:
planet=Mars&Mars=SpaceMissions
The following script will return the value SpaceMissions:
<%= Request.Cookies("planet")("Mars") %>
Setting the cookie path Each cookie stored by ASP in the user's Web browser contains path information. When the browser requests a file whose location is the same as the path specified in the cookie, the browser automatically forwards the cookie to the server. By default, the cookie path corresponds to the application name that contains the .asp file that originally generated the cookie. For example, if an .asp file in an application named UserApplication generates a cookie, then every time the user's Web browser retrieves the file in this application, the browser This cookie is also forwarded to the server.
To declare a path for a cookie that is different from the default application path, use the Path property of ASP's Response.Cookies collection. For example, the following script assigns the path SalesApp/Customer/Profiles/ to a cookie named Purchases:
<%
Response.Cookies("Purchases") = "12"
Response.Cookies("Purchases").Expires = "January 1, 2001"
Response.Cookies("Purchases").Path = "/SalesApp/Customer/Profiles/"
%>
Whenever a web browser that contains the Purchases cookie requests a file located at the path /SalesApp/Customer/Profiles/ or its subdirectories, the browser forwards the cookie to the server.
Many Web browsers, including Microsoft Internet Explorer 4.0 and Netscape browsers, preserve the case of cookie paths. That is, if the case of a requested file is different from the reserved cookie path, the browser will not forward the cookie to the server. For example, to ASP, the virtual directories /TRAVEL and /travel are the same ASP application, but to browsers that preserve URL case, /TRAVEL and /travel are two different applications. You should ensure that all URLs to the .asp file have the same case to ensure that the user's browser can forward the stored cookie.
If desired, you can use the following statement to set the cookie path so that the cookie is forwarded whenever the user's web browser requests a file from your server, regardless of the application or path:
Response.Cookies("Purchases").Path = "/"
However, please note that sending cookies to the server without distinguishing between applications may create security issues if the cookie contains sensitive information that should not be accessible by programs other than the designated application.
Preserving state without using cookies Not all browsers support cookies. Even when using a browser that supports cookies, some users may prefer to turn off cookie support. If your application needs to respond to browsers that do not support cookies, you must use ASP session management.
If you do not use ASP session management, you must write your own mechanism to pass information between your application pages. There are two general ways to accomplish this task:
Add parameters to the URL's query string. For example:
http://MyServer/MyApp/start.asp?name=Jeff
However, some browsers will discard explicit parameters passed in the query string when the form is submitted with the GET method.
Add hidden values to the table. For example, the following HTML table contains an implicit control. This control does not appear in the actual form and is not visible to the user's Web browser. Through the HTTP POST method, the form passes the user ID in addition to the information provided by the user.
<FORM METHOD="POST" ACTION="/scripts/inform.asp">
<INPUT TYPE="text" NAME="city" VALUE="">
<INPUT TYPE="text" NAME="country" VALUE="">
<INPUT TYPE="hidden" NAME="userid" VALUE= <%=UserIDNum(i) %>
<INPUT TYPE="submit" VALUE="Enter">
This method requires that all link targets that transfer user information be encoded as HTML tables.
If you are not currently using ASP session management, turn off session support for your application. When a session is enabled, ASP sends the SessionID cookie to each browser that requests an ASP page. To turn off session support, clear the Enable Session State check box in the Application Options property page in Internet Services Manager.
Sessionless ASP page
ASP also provides the ability to create sessionless pages, which you can use to defer session creation until the user accesses an ASP page that requires session tracking.
Sessionless pages do not perform the following functions:
Execute the Session_OnStart procedure.
Send session ID cookie.
Create Session object.
Access built-in session objects or session-scoped objects created with the <OBJECT> tag.
Executed sequentially with other session requests.
To configure .asp to be sessionless, use the following statement:
<%@ EnableSessionState=False %>
You should place this script on the first line of the .asp file, before other scripts. By default, if this flag is omitted, session tracking is enabled.
Sessionless ASP pages improve server response performance by eliminating potentially time-consuming session operations. For example, consider the following situation: an ASP page contains two HTML frames, Frame 1 and Frame 2, in a frame set. Frame 1 contains an .asp file that executes a complex script, while Frame 2 contains a simple .html file. Because ASP executes session requests sequentially (that is, serially), you will not see the contents of frame 2 until the script for frame 1 is executed. However, if you set frame 1 to sessionless, the ASP request is no longer processed serially, and the browser does not have to wait for the content of frame 1 to finish executing before it can process the content of frame 2.
However, how multiple requests for different frames are handled ultimately depends on the configuration of the user's web browser. Some Web browsers may ignore the sessionless configuration of your .asp file and still handle requests serially.