M0194 Web-based Programming Lanjut Session 2 

advertisement
M0194
Web-based Programming Lanjut
Session 2
 2004 Tau Yenny, SI - Binus
2
Application, Session and Cookies



Application Object
Session Object
Cookies
 2004 Tau Yenny, SI - Binus
3
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.
 2004 Tau Yenny, SI - Binus
4
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
 2004 Tau Yenny, SI - Binus
5
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.
 2004 Tau Yenny, SI - Binus
6
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).
 2004 Tau Yenny, SI - Binus
7
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.
 2004 Tau Yenny, SI - Binus
8
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 bugassociated 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.
 2004 Tau Yenny, SI - Binus
9
The ASP Application Object

Application Object’s Collections
Collection Name
Description
Contents
A collection of the variables (and their values) that are stored in
the Application object, and are not defined using an <OBJECT>
element. This includes Variant arrays and Variant-type object
instance references.
StaticObjects
A collection of the variables that are stored in the Application
object by using an <OBJECT> element.
 2004 Tau Yenny, SI - Binus
10
The ASP Application Object

Application Object’s Methods
Method
Description
Contents.Remove (“variable_name”)
Removes a named variable from the
Application.Contents collection.
Contents.Removeall ( )
Removes all variables from the
Application.Contents collection.
Lock ( )
Locks the Application object so that only the
current ASP pages has access to the
contents. Used to ensure that concurrency
issues do not corrupt the contents by
allowing two users to simultaneously read
and update the values.
Unlock ( )
Releases this ASP page’s lock on the
Application object.
 2004 Tau Yenny, SI - Binus
11
The ASP Application Object

Application Object’s Events
Event
Description
onStart
Occurs when the ASP application starts, before the page that the
user requests is executed and before any user Session objects
are created. Used to initialize variables, create objects, or run
other code.
onEnd
Occurs when the ASP application ends. This is after the last user
session has ended, and after any code in the onEnd event for
that session has executed. All variables existing in the
application are destroyed when it ends.
 2004 Tau Yenny, SI - Binus
12
The ASP Session Object

Session Object’s Collections
Collection Name
Description
Contents
A collection of the variables and their values that are stored in
this particular Session object, and are not defined using an
<OBJECT> element. This includes Variant arrays and Varianttype object instance references.
StaticObjects
A collection of the variables that are stored in this particular
Session object by using an <OBJECT> element.
 2004 Tau Yenny, SI - Binus
13
The ASP Session Object

Session Object’s Properties
Properties
Description
CodePage
Read/write. Integer. Defines the code page that will be used to display
the page content in the browser. The code page is the numeric value of
the character set, and different languages and locales may use different
code pages. For example, ANSI code page is 1252 is used for American
English and most European languages. Code page 932 is used for
Japanese Kanji.
LCID
Read/write. Integer. Defines the locale identifier (LCID) of the page that
is sent to the browser. The LCID is a standard international abbreviation
that uniquely identifies the locale; for instance 2057 defines a locale
where the currency symbol used id ‘₤ ‘. This LCID can also be used in
statements such as FormatCurrency, where there is an optional LCID
argument. The LCID for a page can also be set in the opening <%@..%>
ASP processing directive and overrides the setting in the LCID property
of the session.
 2004 Tau Yenny, SI - Binus
14
The ASP Session Object

Session Object’s Properties
Properties
Description
SessionID
Read/write. Long. Returns the session identifier for this session, which is
generated by the server when the session is created. Uniquely only for
the duration of the parent Application object, and so may be re-used
when a new application is started.
Timeout
Read/write. Integer. Defines the timeout period in minutes for this
Session object. If the user does not refresh or request a page within
timeout period, the session ends. Can be changed in individual page as
required. The default is 10 minutes, and shorter timeouts may be
preferred on a high-usage site.
 2004 Tau Yenny, SI - Binus
15
The ASP Session Object

Session Object’s Methods
Method
Description
Contents.Remove (“variable_name”)
Removes a named variable from the
Session.Contents collection.
Contents.Removeall ( )
Removes all variables from the
Session.Contents collection.
Abandon ( )
Ends the current user session and destroys
the current Session object once execution of
this page is complete. You can still access
the current session’s variables in this page,
even after calling the Abandon method.
However the next ASP page that is
requested by this user will start a new
session, and create a new Session object (if
any exist).
Note that you cannot remove variables from the Session.StaticObjects collection at run-time
 2004 Tau Yenny, SI - Binus
16
The ASP Session Object

Session Object’s Events
Event
Description
onStart
Occurs when the ASP user session starts, before the page that the
user requests is executed. Used to initialize variables, create
objects, or run other code.
onEnd
Occurs when the ASP user session ends. This happends when the
predetermined session timeout period has elapsed since that user’s
last page request from the application. All variables existing in the
session are destroyed when it ends. It is also possible to end ASP
user sessions explicitly in code using the Abandon method, and
this event occurs when that happens.
 2004 Tau Yenny, SI - Binus
17
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.
 2004 Tau Yenny, SI - Binus
18
1.
2.
3.
<!-- Declare instance of the ASPCounter component with application-level scope // -->
<OBJECT ID="ASPCounter" RUNAT="Server" SCOPE="Application“ PROGID="MSWC.Counters">
</OBJECT>
6.
<!-- Declare instance of the ASPContentLink component with Session-level scope // -->
<OBJECT ID="ASPContentLink" RUNAT="Server" SCOPE=“Session“ PROGID="MSWC.NextLink">
</OBJECT>
7.
<SCRIPT LANGUAGE="VBScript" RUNAT="Server">
8.
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
4.
5.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
Sub Application_onEnd()
Set Application("ADOConnection") = Nothing
End Sub
 2004 Tau Yenny, SI - Binus
19
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
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
33.
34.
35.
36.
37.
38.
'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")
39.
40.
41.
42.
43.
44.
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
47.
Sub Session_onEnd()
Set Session("ASPAdRotator") = Nothing
End Sub
48.
</SCRIPT>
45.
46.
 2004 Tau Yenny, SI - Binus
20
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”)
 2004 Tau Yenny, SI - Binus
21
The ASP Processing Directive
Directive Keyword
Description
LANGUAGE=“language_name”
Sets the default scripting language for the page.
For example <%@LANGUAGE=“VBScript” %>
ENABLESESSIONSTATE =
“True” | “False”
When set to “True” prevents a session cookie from
being sent to the browser, and so no new Session
object will be created and any existing session
content will not be available.
CODEPAGE=“code_page”
Sets the code page for the page. For example,
<%@CODEPAGE=“1252”%>
LCID=“locale_identifier”
Sets the locale identifier for the page. For example,
<%@LCID=“2057”%>
 2004 Tau Yenny, SI - Binus
22
The ASP Processing Directive
Directive Keyword
TRANSACTION =
“transaction_type”
Description
Specifies that the page file will run under a transaction
context. Legal issues are :
“Required” : the script wil run within an existing transaction if
one is available, or start a new transaction if not.
“Requires_New” : the script will always initiate a new
transaction.
“Supported” : the script will run within an existing transaction
if one is available, but will not start a new transaction.
“Not_Supported” : the script will not run within any existing
transaction, and will not initiate a new transaction
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” %>
 2004 Tau Yenny, SI - Binus
23
The ASP Application Object In Action
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
<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
%>
 2004 Tau Yenny, SI - Binus
24
The ASP Application Object In Action
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
<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>
 2004 Tau Yenny, SI - Binus
25
The ASP Application Object In Action
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
<%
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>
 2004 Tau Yenny, SI - Binus
26
The ASP Application Object In Action
 2004 Tau Yenny, SI - Binus
27
The ASP Session Object In Action
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
<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
%>
 2004 Tau Yenny, SI - Binus
28
The ASP Session Object In Action
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
<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>
 2004 Tau Yenny, SI - Binus
29
The ASP Session Object In Action
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
<%
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>
 2004 Tau Yenny, SI - Binus
30
The ASP Session Object In Action
 2004 Tau Yenny, SI - Binus
31
The ASP Session Object In Action
abandon.asp
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
<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>
 2004 Tau Yenny, SI - Binus
32
The ASP Session Object In Action
 2004 Tau Yenny, SI - Binus
33
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
 2004 Tau Yenny, SI - Binus
34
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”)
 2004 Tau Yenny, SI - Binus
35
Storing a User’s Details in Cookies
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
<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>
 2004 Tau Yenny, SI - Binus
36
Storing a User’s Details in Cookies
 2004 Tau Yenny, SI - Binus
37
Storing a User’s Details in Cookies
CheckLogin.asp
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
<%
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>
 2004 Tau Yenny, SI - Binus
38
Storing a User’s Details in Cookies
 2004 Tau Yenny, SI - Binus
Download