javascript asp教程第十二课---session对象 Overview: The Session Object is how you track a single user across many pages. It has four (4) properties, two (2) collections, one (1) method, and two (2) events. Get Started: In this series of examples we will create a password system. We will use the Session Object to track whether or not a user is authorized to view certain pages. Below are several scripts for lesson12. Look at them, play with, and then read the explanations that come further down the page. <%@LANGUAGE="JavaScript"%> <% //No ASP Here, just a regular HTML Page %>
To play along with our password page, put in a user name and a password.
The correct user name is guest.
And the correct password is also guest.
Click Here to run script12.asp in a new window. Below is script12a.asp. <%@LANGUAGE="JavaScript"%> <% var userName=new String(Request.Form("userName")) var userPassword=new String(Request.Form("userPassword")) if (userName=="guest" && userPassword=="guest") { Session("Authorized")=true Response.Redirect("script12b.asp") } else { Session("Authorized")=false %>
<% } //end else statement %> We'll skip over script12b.asp entirely because it's almost exactly the same as script12c.asp. Down below is script12c.asp. <%@LANGUAGE="JavaScript"%> <% if (Session("Authorized")!=true) { %>
<% } //end of else statement %> Above is script12c.asp, which is the second of two password-protected pages. Below is script12.asp, which is the logout page. <%@LANGUAGE="JavaScript"%> <% if (Session("Authorized")!=true) { %>
<% } //end of else statement %> A Quick Explanation: After all that, the last thing you want to see is another grey box full of code. Sorry to do it one more time but, the keystone to this system is in script12a.asp. I've reprinted it down below. if (userName=="guest" && userPassword=="guest") { Session("Authorized")=true Response.Redirect("script12b.asp") } Any page can now be turned into a password protected page with the following line: if (Session("Authorized")!=true). Session Variables are part of the Session Collections. Let's talk about them. Session Collections: The two Session Collections are Session.Contents and Session.StaticObjects. They parallel the Application.Contents and Application.StaticObjects. Using Session.Contents("someVariable")="someValue" we can set Session Variables. These variables allow us to carry values from one page to the next. Since Contents is the default collection we can use a little shortcut. It goes like this: Session("someVariable")="someValue". The shortcut is what you saw in the scripts above. Session.Contents has two methods of its own. They are Session.Contents.Remove("variableName") and Session.Contents.RemoveAll(). We did not demonstrate StaticObjects in the scripts above. It comes in the form of the