380 likes | 449 Views
M0194 Web-based Programming Lanjut. Session 2. Application, Session and Cookies. Application Object Session Object Cookies. Managing State on the Web. What Exactly is State?
E N D
M0194 Web-based Programming Lanjut Session 2
Application, Session and Cookies • Application Object • Session Object • Cookies
Managing State on the Web • What Exactly is State? Each client makes a connection to the server and the database application. The connection is normally established by authenticating the user. Authentication is typically a combination of identifying users through a user-name and then making them present a password to prove that they are a valid user. Ability to identify each client’s request, and hold values in memory that are related to just that user, provides state.
Managing State on the Web • Why State So Important? To create Web-based application that interacts with users, it must be able to provide individual state for each user. We need to find a way to persist state for each of our visitors. If we can’t do that, we can’t reasonably expect to do anything that requires more than one ASP page, as the variables and other references in that page are all destroyed when page is finished executing
Managing State on the Web • How we Create State on the Web The usual ways of providing state between page requests and site visits is through cookies. • Anonymous vs. Authenticated Visitors The most obvious method, implemented by many sites, is to pop up a login dialog. This authenticates you as a known and valid user, at which point a cookie can be place on your system to hold either the login details, or just a ‘key’ to indicate that you have been identified. • No more Anonymous Visitors A new Session object is created for the first access an ASP page on our server. A session identifier number is allocated to the session, and a cookie containing a specially encrypted version of the session identifier is sent to the client. Every time that this user access an ASP page, ASP looks for this cookie.
ASP Application • Associated with two main topics: • The provision of global scope, through a globally accessible variable storage area • The integration with IIS through COM+, which allow us to better manage components • What can we store in an application ? • Simple variables, such as strings and numbers (stored as Variants like all ASP script variables) • Variant-type arrays, made up of one or more dimensions • Variable references (again as Variants) that point to an instance of a COM object A Variant is the only variable type provided in the VBScript scripting engine for ASP (and Internet Explorer).
ASP Sessions • The ASP application object can be used to store state that is global. • We can use the same name for each variable. • The same code would work transparently for each visitor because it would access that visitor’s own private storage area.
ASP Sessions • Problem with Sessions • Some browsers and Web servers are case sensitive as far as URLs, paths and filenames are concerned. If a cookie has a path specified, and it is different to the path specified in a hyperlink in term of case, the browser may not return it to the server along with a page requested from that directory. • In previous version of IIS and ASP, there were some minor bug-associated problems with nested applications. These have been fixed in ASP 3.0 • Session depend on cookies. Visitors that have cookies disabled, or whose browser doesn’t support them, won’t get a session started and so will not have access to a Session object.
The ASP Application Object • Application Object’s Collections
The ASP Application Object • Application Object’s Methods
The ASP Application Object • Application Object’s Events
The ASP Session Object • Session Object’s Collections
The ASP Session Object • Session Object’s Properties
The ASP Session Object • Session Object’s Properties
The ASP Session Object • Session Object’s Methods Note that you cannot remove variables from the Session.StaticObjects collection at run-time
The ASP Session Object • Session Object’s Events
Using Application and Session Events • ASP raises event each time an application or session starts or ends. • We can detect and react by writing normal script code in a special file – global.asa – located in the root directory of an application. • This file can also contain one or more HTML <OBJECT> elements, used to create component instances that will be used within that application or user’s sessions. The following code is an example global.asa file.
<!-- Declare instance of the ASPCounter component with application-level scope // --> • <OBJECT ID="ASPCounter" RUNAT="Server" SCOPE="Application“ PROGID="MSWC.Counters"> • </OBJECT> • <!-- Declare instance of the ASPContentLink component with Session-level scope // --> • <OBJECT ID="ASPContentLink" RUNAT="Server" SCOPE=“Session“ PROGID="MSWC.NextLink"> • </OBJECT> • <SCRIPT LANGUAGE="VBScript" RUNAT="Server"> • Sub Application_onStart() • 'create an instance of an ADO Recordset with application-level scope • Set Application("ADOConnection") = Server.CreateObject ("ADODB.Connection") • Dim varArray(3) 'create a Variant array and fill it • varArray(0) = "This is a" • varArray(1) = "Variant array" • varArray(2) = "stored in the" • varArray(3) = "Application object" • Application("Variant_Array") = varArray 'store it in the Application • Application("Start_Time") = CStr(Now) 'store the date/time as a string • Application("Visit_Count") = 0 'set counter variable to zero • End Sub • Sub Application_onEnd() • Set Application("ADOConnection") = Nothing • End Sub
Sub Session_onStart() • 'Create an instance of the Adrotator component with session-level scope • Set Session("ASPAdRotator") = Server.CreateObject("MSWC.AdRotator") • Dim varArray(3) 'create a Variant array and fill it • varArray(0) = "This is a" • varArray(1) = "Variant array" • varArray(2) = "stored in the" • varArray(3) = "Session object" • Session("Variant_Array") = varArray 'store it in the Session • Session("Start_Time") = CStr(Now) 'store the date/time as a string • 'We can access the contents of the Request and Response in a Session_onStart • 'event handler for the page that initiated the session. This is the *only* • 'place that the ASP page context is available like this. • 'as an example, we can get the IP address of the user: • Session("Your_IP_Address") = Request.ServerVariables("REMOTE_ADDR") • Application.Lock 'prevent concurrent updates • intVisits = Application("Visit_Count") + 1 'increment counter variable • Application("Visit_Count") = intVisits 'store back in Applcation • Application.Unlock 'Release lock on Application • End Sub • Sub Session_onEnd() • Set Session("ASPAdRotator") = Nothing • End Sub • </SCRIPT>
Using Application and Session Events • Reading and Storing Values • To set the values : Application(“variable_name”) = variable_value Application(“variable_name”) = variant_array_variable_name Set Application(“variable_name”) = object_reference • To retrieve the values: variable_value =Application(“variable_name”) variant_array_variable_name = Application(“variable_name”) Set object_reference = Application(“variable_name”)
The ASP Processing Directive We can include more than one in our processing directive – they must be separated by a space, with no spaces around the equals sign, for example : <%@LANGUAGE=“VBScript” CODEPAGE=“1252” LCID=“2057” %>
The ASP Application Object In Action • <HTML> • <BODY> • <% • Response.Write "<H2> The ASP Application Object</H2> • Response.Write "<STRONG>The Application.Contents Collection</STRONG><BR>" • For Each objItem in Application.Contents • If IsObject(Application.Contents(objItem)) Then • Response.Write "Object Reference: '" & objItem & "'<BR>" • ElseIf IsArray(Application.Contents(objItem)) Then • Response.Write "Array: '" & objItem & "' contents are :<BR>" • varArray = Application.Contents(objItem) • For intLoop = 0 To Ubound(varArray) • Response.Write " Index(" & intLoop & ") = " & varArray(intLoop) & "<BR>" • Next • Else • Response.Write "Variable: '" & objItem & "' = " & Application.Contents(objItem) & "<BR>" • End If • Next • Response.Write "<BR><STRONG>The Application.StaticObjects Collection</STRONG><BR>" • For Each objItem in Application.StaticObjects • If IsObject(Application.StaticObjects(objItem)) Then • Response.Write "<OBJECT> element: ID='" & objItem & "'<BR>“ • End If • Next • %>
The ASP Application Object In Action • <H2>Add a value to the Application Object</H2> • <FORM ACTION="<%=Request.ServerVariables("SCRIPT_NAME") %>" METHOD="POST"> • <INPUT TYPE="SUBMIT" NAME="cmdAdd" VALUE=" "> • Application(" • <INPUT TYPE="TEXT" NAME="txtVarName" VALUE=""> • ")=" • <INPUT TYPE="TEXT" NAME="txtVarValue" VALUE=""> • " • <BR> • <H2> Remove a value from the Application Object</H2> • <INPUT TYPE="SUBMIT" NAME="cmdRemove" VALUE=" "> • Application.Contents.Remove(" • <SELECT NAME="lstRemove" Size = "1"> • <% • For Each objItem in Application.Contents • Response.Write "<OPTION> " & objItem & "</OPTION>" • Next • %> • </SELECT> • ") • <BR> • <INPUT TYPE="SUBMIT" NAME="cmdRemoveAll" VALUE=" "> • Application.Contents.RemoveAll • </FORM>
The ASP Application Object In Action • <% • If Len(Request.Form("cmdAdd")) Then • strVarName = Request("txtVarName") • strVarValue = Request("txtVarValue") • Application.Lock • Application(strVarname) = strVarValue • Application.Unlock • End If • If Len(Request.Form("cmdRemove")) Then • strToRemove = Request.Form("lstRemove") • Application.Lock • Application.Contents.Remove(strToRemove) • Application.Unlock • End If • If Len(Request.Form("cmdRemoveAll")) Then • Application.Lock • Application.Contents.RemoveAll • Application.Unlock • End If • %> • </BODY> • </HTML>
The ASP Session Object In Action • <HTML> • <HEAD> <TITLE>The Session Object</TITLE> </HEAD> • <BODY> • <% • Response.Write "<H2>The ASP Session Object</H2><STRONG>The Session.Contents Collection</STRONG><BR>" • For Each objItem in Session.Contents • If IsObject(Session.Contents(objItem)) Then • Response.Write "Object Reference: '" & objItem & "'<BR>" • ElseIf IsArray(Session.Contents(objItem)) Then • Response.Write "Array: '" & objItem & "' contents are :<BR>" • varArray = Session.Contents(objItem) • For intLoop = 0 To Ubound(varArray) • Response.Write " Index(" & intLoop & ") = " & varArray(intLoop) & "<BR>" • Next • Else • Response.Write "Variable: '" & objItem & "' = " & Session.Contents(objItem) & "<BR>" • End If • Next • Response.Write "<BR><STRONG>The Session.StaticObjects Collection</STRONG><BR>" • For Each objItem in Session.StaticObjects • If IsObject(Session.StaticObjects(objItem)) Then • Response.Write "<OBJECT> element: ID='" & objItem & "'<BR>" • End If • Next • Response.Write "<BR><STRONG>Property Values</STRONG><BR>" • Response.Write "Session.CodePage = " & Session.CodePage • Response.Write "; Session.LCID = " & Session.LCID • Response.Write "; Session.SessionID = " & Session.SessionID • Response.Write "; Session.TimeOut = " & Session.TimeOut • %>
The ASP Session Object In Action • <FORM ACTION="<%=Request.ServerVariables("SCRIPT_NAME") %>" METHOD="POST"> • <H4>Add a value to the Session Object</H4> • <INPUT TYPE="SUBMIT" NAME="cmdAdd" VALUE=" "> • Session(" • <INPUT TYPE="TEXT" NAME="txtVarName" VALUE=""> • ")=" • <INPUT TYPE="TEXT" NAME="txtVarValue" VALUE=""> • " • <BR><H4> Remove a value from the Session Object</H4> • <INPUT TYPE="SUBMIT" NAME="cmdRemove" VALUE=" "> • Session.Contents.Remove(" • <SELECT NAME="lstRemove" Size = "1"> • <% • For Each objItem in Session.Contents • Response.Write "<OPTION> " & objItem & "</OPTION>" • Next • %> • </SELECT> • ") • <BR><INPUT TYPE="SUBMIT" NAME="cmdRemoveAll" VALUE=" "> • Session.Contents.RemoveAll • <BR><H4>Terminating This Session</H4> • <INPUT TYPE="SUBMIT" NAME="cmdAbandon" VALUE=" "> • Session.Abandon • </FORM>
The ASP Session Object In Action • <% • If Len(Request.Form("cmdAdd")) Then • strVarName = Request("txtVarName") • strVarValue = Request("txtVarValue") • Session(strVarname) = strVarValue • End If • If Len(Request.Form("cmdRemove")) Then • strToRemove = Request.Form("lstRemove") • Session.Contents.Remove(strToRemove) • End If • If Len(Request.Form("cmdRemoveAll")) Then • Session.Contents.RemoveAll • End If • If Len(Request.Form("cmdAbandon")) Then • Response.Clear • Response.Redirect "abandon.asp“ • Response.End • End If • %> • </BODY> • </HTML>
The ASP Session Object In Action abandon.asp • <HTML> • <HEAD> • <TITLE>Terminated Session</TITLE> • </HEAD> • <BODY> • <% Session.Abandon %> • <FORM ACTION="<%=Request.ServerVariables("HTTP_REFERER") %>" METHOD="POST"> • <P><DIV Style = "Background-color:#FFCCFF; text-align:center">Your Session Has Been Terminated</DIV> • <P>A new <STRONG>Session</STRONG> will be started when you load another<BR> • ASP Page. It will contain any values that are defined in<BR> • the <STRONG>global.asa</STRONG> file for this application. • <P><INPUT TYPE="SUBMIT" NAME="cmdOk" VALUE=" "> • Return to the previous page<P> • </BODY> • </HTML>
Cookies • Small chunks of text that are stored on the client’s system by their browser. • Sent to the server with every request for a page from the domain to which they apply. • Request.Cookies collection is read-only. • Response.Cookies collection is write-only. • Contain information in two ways: • single value • multiple-values
Cookies • Creating a single value cookie Response.Cookies(“item-name”) = “item-value” • Creating a cookie contain multiple values Response.Cookies(“item-name”)(“sub-item-name”) = “sub-item-value” • To set the domain and path to which a cookie applies, and it’s expiry date : Response.Cookies(“item-name”).domain = “domain-url” Response.Cookies(“item-name”).path = “virtual-path” Response.Cookies(“item-name”).expires = #date# If the Expires property is not set, the cookie will be destroyed when user closes the current browser instance. • To read the values of existing cookies: strSingleValue = Request.Cookies(“item-name”) strSubItemValue = Request.Cookies (“item-name”)(“sub-item-name”)
Storing a User’s Details in Cookies • <HTML> • <HEAD> • <TITLE>Cookie Test - Login</TITLE> • </HEAD> • <BODY> • Please enter your e-mail address and password to login to the system. • <FORM ACTION = "CheckLogin.asp" METHOD="POST" > • E-Mail Address: <INPUT TYPE = "Text" NAME = "Email" SIZE = "40"><BR> • Password: <INPUT TYPE = "Password" NAME = "Password" SIZE = "10"><P> • <INPUT TYPE = "Checkbox" NAME = "SaveLogin"> Save Login as a Cookie?<P> • <INPUT TYPE = "Submit" VALUE = "Login"> • <INPUT TYPE = "RESET"> • </FORM> • </BODY> • </HTML>
Storing a User’s Details in Cookies CheckLogin.asp • <% • Dim bLoginSaved • If Request.Form("SaveLogin") = "on" Then • Response.Cookies("SavedLogin")("EMail") = Request.Form("email") • Response.Cookies("SavedLogin")("pw") = Request.Form("password") • Response.Cookies("SavedLogin").Expires = Date + 30 • bLoginSaved = True • Else • bLoginSaved = False • End If • %> • <HTML> • <HEAD> • <TITLE>Cookie Test - Check Login</TITLE> • </HEAD> • <BODY> • <% • If bLoginSaved Then • Response.Write "Saving Login information to a cookie<HR>" • End If • %> • Thank you for logging into the system.<P> • E-Mail address confirmation: <%= Request.Form("email")%> • </BODY> • </HTML>