Sie sind auf Seite 1von 31

The Session object

When you are working with an application, you open it, do some changes and then
you close it. This is much like a Session. The computer knows who you are. It
knows when you start the application and when you end. But on the internet there
is one problem: the HTTP address doesn't maintain state so that the web server
does not know who you are and what you do.
By creating a unique cookie for each user,ASP solves this problem . The cookie is
sent to the client and it contains information that identifies the user. This interface
is called the Session object.
For a user session,the Session object is used to store information about, or
change settings . Session object is a variable that holds information about one
single user, and are available to all pages in one application. Common information
stored in session variables are name, id, and preferences. The server creates a
new Session object for each new user, and destroys the Session object when the
session expires.

When does a Session Start?


A session starts when:
• After a new user requests an ASP file, and the Global.asa file includes a
Session_OnStart procedure
• In a Session variable,a value is stored.
• To instantiate an object with session scope a user requests an ASP file, and
the Global.asa file uses the <object> tag.

When does a Session End?

If a user has not requested or refreshed a page in the application for a specified
period,a session ends . By default, this is 20 minutes.
you can set the Timeout property if you want to set a timeout interval that is
shorter or longer than the default,
The example below sets a timeout interval of 10 minutes:

<%
Session.Timeout=10
%>

You may use the Abandon method to end a session immediately:

<%
Session.Abandon
%>
Note: WHEN they should end is the main problem with sessions. If the user's last
request was the final one or not we do not know. So how long we should keep the
session "alive", we do not know. Waiting too long for an idle session uses up
resources on the server, but the user has to start all over again because the
server has deleted all the information if the session is deleted too soon. Finding
the right timeout interval can be difficult!
Tip: If you are using session variables, store SMALL amounts of data in them.

Store and Retrieve Session Variables

You can store variables in it is the most important thing about the Session object .
.
The example below will set the Session variable username to "Martin Luther" and
the Session variable age to "40":

<%
Session("username")="Martin Luther"
Session("age")=40
%>

It can be reached from ANY page in the ASP application if the value is stored in a
session variable :

Welcome <%Response.Write(Session("username"))%>

The above example returns: "Welcome Martin Luther".


In the Session object,you can also store user preferences and then access that
preference to choose what page to return to the user.
If the user has a low screen resolution,the example below specifies a text-only
version of the page

<%If Session("screenres")="low" Then%>


This is the text version of the page
<%Else%>
This is the multimedia version of the page
<%End If%>

Remove Session Variables

All session variables are stored in Contents collection


To remove a session variable with the Remove method is possible.
If the value of the session variable "age" is lower than 18,the example below
removes the session variable "sale"

<%
If Session.Contents("age")<18 then
Session.Contents.Remove("sale")
End If
%>

Use the RemoveAll method to remove all variables in a session,:

<%
Session.Contents.RemoveAll()
%>

Loop Through the Contents Collection

All session variables are stored in Contents collection .To see what's stored in it
,you can loop through the Contents collection, :

<%
Session("username")="Donald Duck"
Session("age")=50
dim i
For Each i in Session.Contents
Response.Write(i & "<br />")
Next
%>

• An application is a group of ASP files that work together to perform


some purpose

• In ASP,the Application object is used to tie these files together.

Application Object

A group of ASP files may be called an application on the Web . Some purpose can
be achieved when the ASP file work together.In ASP ,the Application object is used
to tie these files together.
For storing and accessing variables from any page, just like the Session object,the
Application object is used . The difference is that in Sessions there is one Session
object for EACH user while ALL users share one Application object .
In the Particular application (like database connection information),the Application
object should hold information that will be used by many pages . This means it is
possible access the information from any page. In an Application object , you can
change the information in one place and the changes will automatically be
reflected on all pages.

Store and Retrieve Application Variables

In the application,application variables can be accessed and changed by any


page .
You can create Application variables using "Global.asa" like this:

<script language="vbscript" runat="server">

Sub Application_OnStart
application("vartime")=""
application("users")=1
End Sub

</script>

In the example above we have created two Application variables: "vartime" and
"users".
Application variables can be accessed like this:

There are
<%
Response.Write(Application("users"))
%>
active connections

Lock and Unlock

• Using "Lock" method,you can lock an application


• The users cannot change the Application variables(other than the one
currently accessing it),when an application is locked .
• Using "Unlock" method,you can unlock an application
• This method is used to remove the lock from the Application variable:>

<%
Application.Lock
'do some application object operations
Application.Unlock
%>

The #include Directive

• With the help of the #include directive, you can insert the content of one
ASP file into another ASP file before the server executes it
• To create functions, headers, footers, or elements that will be reused on
multiple pages,the #include directive is used.

How to Use the #include Directive


Here is a file called "mypage.asp":

<html>
<body>
<h3>Words of Wisdom:</h3>
<p><!--#include file="wisdom.inc"--></p>
<h3>The time is:</h3>
<p><!--#include file="time.inc"--></p>
</body>
</html>

Here is the "wisdom.inc" file:

"One should never increase, beyond what is necessary, the number of entities
required to explain anything."

Here is the "time.inc" file:

<%
Response.Write(Time)
%>

If you look into the browser to see the source code, it will look something like this:

<html>
<body>
<h3>Words of Wisdom:</h3>
<p>"One should never increase, beyond what is necessary,
the number of entities required to explain anything."</p>
<h3>The time is:</h3>
<p>11:33:42 AM</p>
</body>
</html>

Syntax for Including Files

Place the #include directive inside comment tags to include a file in an ASP page,:

<!--#include virtual="somefilename"-->
or
<!--#include file ="somefilename"-->

The Virtual Keyword

To indicate a path beginning with a virtual directory ,use the virtual keyword .
The following line would insert the contents of "header.inc" if a file named
"header.inc" resides in a virtual directory named /html :

<!-- #include virtual ="/html/header.inc" -->

The File Keyword

To indicate a relative path ,file keyword is used. A relative path begins with the
directory that contains the including file.
The following line would insert the contents of "header.inc" if a file named
"header.inc" resides in a virtual directory named /html,

<!-- #include file ="headers\header.inc" -->

Note that the path to the included file (headers\header.inc) is relative to the
including file. If the file containing this #include statement is not in the html
directory, the statement will not work.
To include a file from a higher-level directory,you can also use the file keyword
with the syntax (..\)

Tips and Notes

In the sections above we have used the file extension ".inc" for included files.
Notice that if a user tries to browse an INC file directly, its content will be
displayed. If your included file contains confidential information or information you
do not want any users to see, it is better to use an ASP extension. The source
code in an ASP file will not be visible after the interpretation. An included file can
also include other files, and one ASP file can include the same file more than once.
Important: Included files are processed and inserted before the scripts are
executed.
The following script will not work because before it assigns a value to the
variable ,ASP executes the #include directive:

<%
fname="header.inc"
%>
<!--#include file="<%=fname%>"-->

In an INC file,you cannot open or close a script delimiter . This script will not
work:

<%
For i = 1 To n
<!--#include file="count.inc"-->
Next
%>

But this script will work:

<% For i = 1 to n %>


<!--#include file="count.inc" -->
<% Next %>

The Global.asa file

In an ASP application,the Global.asa file is an optional file that stores declarations


of objects, variables, and methods that can be accessed by every page .
Global.asa file uses all valid browser scripts (JavaScript, VBScript, JScript,
PerlScript, etc.) The Global.asa file stores only the following:
• Application events
• Session events
• <object> declarations
• TypeLibrary declarations
• the #include directive
Note: Each application can only have one Global.asa file and the Global.asa file
must be stored in the root directory of the ASP application.

Events in Global.asa

when the application/session starts or application/session ends ,it is necessary to


tell the application and session objects in Glogal.asa about the work to be done.
The code for this is placed in event handlers. The Global.asa file uses four types of
events:
Application_OnStart - This event occurs in an ASP application when the FIRST
user calls the first page from . This event occurs after the Global.asa file is edited
or after the Web server is restarted. The "Session_OnStart" event occurs
immediately after this event.
Session_OnStart - In the ASP application,this event occurs EVERY time a NEW
user requests his or her first page .
Session_OnEnd - EVERY time a user ends a session, this event occurs. After a
page has not been requested by the user for a specified time (by default this is 20
minutes),a user ends a session .
Application_OnEnd - Aafter the LAST user has ended the session,this event
occurs. Typically, this event occurs when a Web server stops. To clean up settings
after the Application stops,this procedure is used like delete records or write
information to text files.
A Global.asa file could look something like this:

<script language="vbscript" runat="server">


sub Application_OnStart
'some code
end sub
sub Application_OnEnd
'some code
end sub
sub Session_OnStart
'some code
end sub
sub Session_OnEnd
'some code
end sub
</script>

Because to insert scripts in the Global.asa file we cannot use the ASP script
delimiters (<% and %>), we put subroutines inside an HTML <script> element

<object> Declarations

With the help of <object> tag it is possible to create objects with session or
application scope in Global.asa .
Note: The <object> tag should be outside the <script>tag
Syntax:

<object runat="server" scope="scope" id="id"


{progid="progID"|classid="classID"}>
....
</object>

Paramete
Description
r
scope Sets the scope of the object (either Session or Application)
id Specifies a unique id for the object
An id associated with a class id. The format for ProgID is
ProgID [Vendor.]Component[.Version]
Either ProgID or ClassID must be specified.

Specifies a unique id for a COM class object.


ClassID
Either ProgID or ClassID must be specified.

Examples

The first example creates an object of session scope named "MyCreate" by using
the ProgID parameter:

<object runat="server" scope="session" id="MyCreate"


progid="MSWC.AdRotator">
</object>

The second example creates an object of application scope named "MyConnection"


by using the ClassID parameter:

<object runat="server" scope="application" id="MyConnection"


classid="Clsid:8AD3067A-B3FC-11CF-A560-00A0C9081C21">
</object>

In the application,the objects declared in the Global.asa file can be used by any
script :

GLOBAL.ASA:<object runat="server" scope="session" id="MyAd"


progid="MSWC.AdRotator">
</object>
You could reference the object "MyAd" from any page in the ASP application:
SOME .ASP FILE:

<%=MyAd.GetAdvertisement("/banners/adrot.txt")%>

TypeLibrary Declarations

A TypeLibrary is a container that stores DLL file corresponding to a COM object. By


including a call to the TypeLibrary in the Global.asa file, the constants of the COM
object can be accessed, and errors can be better reported by the ASP code. You
can declare the type libraries in Global.asa if your Web application relies on COM
objects that have declared data types in type libraries,

Syntax

<!--METADATA TYPE="TypeLib"
file="filename"
uuid="typelibraryuuid"
version="versionnumber"
lcid="localeid"
-->

Paramete
Description
r

Specifies an absolute path to a type library.


file
Either the file parameter or the uuid parameter is required
Specifies a unique identifier for the type library.
uuid
Either the file parameter or the uuid parameter is required

Optional. Used for selecting version. If the requested version is not


Version
found, then the most recent version is used

lcid Optional. The locale identifier to be used for the type library

Error Values

The following error messages can return by the server :

Error Code Description

ASP 0222 Invalid type library specification

ASP 0223 Type library not found


ASP 0224 Type library cannot be loaded
ASP 0225 Type library cannot be wrapped

Note:
In the Global.asa file, METADATA tags can appear anywhere (both inside and
outside <script> tags). However, it is recommended that METADATA tags appear
near the top of the Global.asa file.

Restrictions
You can include restrictions in the Global.asa file:
• The text that is written in the Global.asa file can not be displayed. This file
can't display information
• in the Application_OnStart and Application_OnEnd subroutines,you can only
use Server and Application objects . In the Session_OnEnd subroutine, you
can use Server, Application, and Session objects. You can use any built-in
object in the Session_OnStart subroutine

How to use the Subroutines

To initialize variables. Global.asa is often used.


The example below shows how to detect the exact time a visitor first arrives on a
Web site. The time is stored in a Session variable named "started", and in the
application,the value of the "started" variable can be accessed from any ASP
page :

<script language="vbscript" runat="server">


sub Session_OnStart
Session("started")=now()
end sub
</script>

To control page access, Global.asa can also be used .


The example below shows how to redirect every new visitor to another page, in
this case to a page called "newpage.asp":

<script language="vbscript" runat="server">


sub Session_OnStart
Response.Redirect("newpage.asp")
end sub
</script>
And you can include functions in the Global.asa file.
In the example below when the Web server starts,the Application_OnStart
subroutine occurs . Then the Application_OnStart subroutine calls another
subroutine named "getusers". The "getusers" subroutine opens a database and
retrieves a record set from the "users" table. The record set is assigned to an
array, where it can be accessed from any ASP page without querying the database

<script language="vbscript" runat="server">


sub Application_OnStart
getusers
end sub
sub getusers
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"
set rs=conn.execute("select name from users")
Application("users")=rs.GetRows
rs.Close
conn.Close
end sub

Global.asa Example

In this example we will create a Global.asa file that counts the number of current
visitors.
• When the server starts,the Application_OnStart sets the Application
variable "visitors" to 0
• Every time a new visitor arrives,the Session_OnStart subroutine adds one
to the variable "visitors"
• The Session_OnEnd subroutine subtracts one from "visitors" each time
this subroutine is triggered
The Global.asa file:

<script language="vbscript" runat="server">


Sub Application_OnStart
Application("visitors")=0
End Sub
Sub Session_OnStart
Application.Lock
Application("visitors")=Application("visitors")+1
Application.UnLock
End Sub
Sub Session_OnEnd
Application.Lock
Application("visitors")=Application("visitors")-1
Application.UnLock
End Sub
</script>

In an ASP file,to display the number of current visitors is given below:

<html>
<head>
</head>
<body>
<p>
There are <%response.write(Application("visitors"))%> online now!
</p>
</body>
</html>

BEFORE YOU START READ THIS:

In order to send Email from an ASP page on your Web Site, your (Windows / IIS /
NT {wossat?}) Web Host needs to have one of the proprietary mailing
components installed. Think of these "Components" as "Plug In" programs that
add extra functionality to the server. ASK YOUR HOST what they are running and
ASK THEM for some working script examples. If they can't provide you with
these. Dump them!

 "Can I test my email routines from my own computer?" Probably not.


Assuming you are running XP Pro and have IIS 5.1 installed, you would first have
to set up and configure the SMTP server and then install and configure any server
components that you want to use. Also, the ISP that you use will probably have a
policy of not accepting the relay or transfer of mail originating from addresses
outside of their own domain. This is a security measure to prevent their servers
being used for relaying spam. All in all, it is not an impossible task to set up you
own mail server, but it's one that falls way outside of the purpose of this tutorial

Basic CDONTS Mailing Script:

There are eight basic mailing scripts below I have included for you to play with.
Each of these scripts uses a different kind of mailing component. THE SCRIPTS
WILL ONLY WORK ON A SERVER THAT HAS THE RELEVANT COMPONENT
INSTALLED ON IT. Check with your host to find out what they are running.
Actually, you should have done that before you signed up with them.
Use the basic script examples below and get them working properly FIRST before
you start messing with forms and thingsOnce you have established what mailing
components they have installed,.

ASP Code:
<%
Dim myMail
Set myMail = Server.CreateObject ("CDONTS.NewMail")
myMail.From = "You@YourDomain.co.uk"
myMail.To = "YouAgain@YourOtherAddress.co.uk"
myMail.Subject = "Test email using CDONTS"
myMail.Body = "This is a test email message" & vbcrlf & "sent with CDONTS"
myMail.Send
set myMail=nothing
Response.Write("Your e-mail has been sent")
%>

How about CDONTs?

Microsoft has discontinued the use of CDONTs on Windows 2000, Windows XP and
Windows 2003. You should update the code and use the new CDO technology,if
you have used CDONTs in your ASP applications.

Sending a text e-mail using a remote server:


ASP Code:

<%
Set myMail=CreateObject("CDO.Message")
myMail.Subject="Sending email with CDO"
myMail.From="mymail@mydomain.com"
myMail.To="someone@somedomain.com"
myMail.TextBody="This is a message."
myMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing")=2
'Name or IP of remote SMTP server
myMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver") _
="smtp.server.com"
'Server port
myMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") _ =25
myMail.Configuration.Fields.Update
myMail.Send
set myMail=nothing
%>

Sending a text e-mail with Bcc and CC fields:


ASP Code:

<%
Set myMail=CreateObject("CDO.Message")
myMail.Subject="Sending email with CDO"
myMail.From="mymail@mydomain.com"
myMail.To="someone@somedomain.com"
myMail.Bcc="someoneelse@somedomain.com"
myMail.Cc="someoneelse2@somedomain.com"
myMail.TextBody="This is a message."
myMail.Send
set myMail=nothing
%>

Sending an HTML e-mail that sends a webpage from a website:


ASP Code:

<%
Set myMail=CreateObject("CDO.Message")
myMail.Subject="Sending email with CDO"
myMail.From="mymail@mydomain.com"
myMail.To="someone@somedomain.com"
myMail.CreateMHTMLBody "http://www.designs.univdatabase.com/asp/"
myMail.Send
set myMail=nothing
%>

Sending an HTML e-mail that sends a webpage from a file on your


computer:
ASP Code:

<%
Set myMail=CreateObject("CDO.Message")
myMail.Subject="Sending email with CDO"
myMail.From="mymail@mydomain.com"
myMail.To="someone@somedomain.com"
myMail.CreateMHTMLBody "file://c:/mydocuments/test.htm"
myMail.Send
set myMail=nothing
%>

Sending an HTML e-mail:


ASP Code:

<%
Set myMail=CreateObject("CDO.Message")
myMail.Subject="Sending email with CDO"
myMail.From="mymail@mydomain.com"
myMail.To="someone@somedomain.com"
myMail.HTMLBody = "<h1>This is a message.</h1>"
myMail.Send
set myMail=nothing
%>

Sending a text e-mail with an Attachment:


ASP Code:

<%
Set myMail=CreateObject("CDO.Message")
myMail.Subject="Sending email with CDO"
myMail.From="mymail@mydomain.com"
myMail.To="someone@somedomain.com"
myMail.TextBody="This is a message."
myMail.AddAttachment "c:\mydocuments\test.txt"
myMail.Send
set myMail=nothing
%>

Basic ASPMail Mailing Script:


ASP Code:

<%
Dim MyMail
Set MyMail = Server.CreateObject("SMTPsvg.Mailer")
MyMail.FromName = "Fred Bloggs"
MyMail.FromAddress= "You@YourAddress.co.uk"
MyMail.RemoteHost = "mail.yourdomain.co.uk"
MyMail.AddRecipient= "Joe Bloggs ", "YouAgain@YourOtherAddress.co.uk"
MyMail.Subject = "Test email using ASPMail"
MyMail.BodyText = "This is a test email message" & vbcrlf &"sent with ASPMail"
MyMail.SendMail
Set MyMail = nothing
Response.Write("Your e-mail has been sent")
%>

Response Object

To send output to the user from the server,the ASP Response object is used. Its
collections, properties, and methods are described below:
Collections:

Collectio
Description
n

Sets a cookie value. If the cookie does not exist, it will be created,
Cookies
and take the value that is specified

Properties

Property Description
Buffer Specifies whether to buffer the page output or not
Sets whether a proxy server can cache the output generated
CacheControl
by ASP or not
Appends the name of a character-set to the content-type
Charset
header in the Response object
ContentType Sets the HTTP content type for the Response object

Sets how long (in minutes) a page will be cached on a


Expires
browser before it expires

Sets a date and time when a page cached on a browser will


ExpiresAbsolute
expire
IsClientConnecte
Indicates if the client has disconnected from the server
d
Pics Appends a value to the PICS label response header
Status Specifies the value of the status line returned by the server

Methods

Method Description
AddHeader Adds a new HTTP header and a value to the HTTP response
AppendToLo
Adds a string to the end of the server log entry
g
Writes data directly to the output without any character
BinaryWrite
conversion
Clear Clears any buffered HTML output
End Stops processing a script, and returns the current result
Flush Sends buffered HTML output immediately
Redirect Redirects the user to a different URL
Write Writes a specified string to the output
Write text with ASP

<html>
<body>

<%
response.write("Hello World!")
%>

</body>
</html>

O/P:

Hello World!

Format text with HTML tags in ASP

<html>
<body>
<%
response.write("<h2>You can use HTML tags to format the text!</h2>")
%>

<%
response.write("<p style='color:#0000ff'>This text is styled with the style
attribute!</p>")
%>
</body>
</html>

O/P:

You can use HTML tags to format the text!


This text is styled with the style attribute!

Redirect the user to a different URL

<%
if Request.Form("select")<>"" then
Response.Redirect(Request.Form("select"))
end if
%>

<html>
<body>

<form action="demo_redirect.asp" method="post">

<input type="radio" name="select"


value="demo_server.asp">
Server Example<br>

<input type="radio" name="select"


value="demo_text.asp">
Text Example<br><br>
<input type="submit" value="Go!">

</form>

</body>
</html>

O/P:

Server Example

Text Example

Go!

Demonstrates the use of the write method. To write to the browser.

<%@ Language=VBScript%>
<% strFileTitle = "Writing"%>
<%ifnotLCase(Request.QueryString("PageView")) = "source" then%>
<%ShowHeader strFileTitle%>
<%< Response.Write "<HTML>"
Response.Write "<HEAD>"
Response.Write "<META NAME=""GENERATOR"" Content=""Microsoft Visual
Studio 6.0"">"
Response.Write "</HEAD>"
Response.Write "<BODY>"
Response.Write "This example is done completely using Response.Write
statement.<BR><BR>"
Response.Write "If you need to produce quotation marks you use
&quot;&quot;"
Response.Write "</BODY>"
Response.Write "</HTML>"
ShowFooter
%>

O/P:

This example is done completely using Response.Write statement.

If you need to produce quotation marks you use ""

Request Object

It is called a request when a browser asks for a page from a server, . To get
information from the user,the ASP Request object is used. Its collections,
properties, and methods are described below:

Collections:

Collection Description
ClientCertificat
Contains all the field values stored in the client certificate
e

Cookies Contains all the cookie values sent in a HTTP request

Contains all the form (input) values from a form that uses the
Form
post method

QueryString Contains all the variable values in a HTTP query string

ServerVariable
Contains all the server variable values
s

Properties

Property Description

TotalByte Returns the total number of bytes the client sent in the body of the
s request

Methods

Method Description
BinaryRea Retrieves the data sent to the server from the client as part of a
d post request and stores it in a safe array

Send query information when a user clicks on a link using QueryString

<html>
<body>

<a href="demo_simplequerystring.asp?color=green">Example</a>

<%
Response.Write(Request.QueryString)
%>

</body>
</html>

O/P:

Example color=green

How to use information from forms

<html>
<body>
<form action="demo_simpleform.asp" method="post">
Your name: <input type="text" name="fname" size="20" />
<input type="submit" value="Submit" />
</form>
<%
dim fname
fname=Request.Form("fname")
If fname<>"" Then
Response.Write("Hello " & fname & "!<br />")
Response.Write("How are you today?")
End If
%>
</body>
</html>

O/P:

Ravi Submit

Your Name:

Results:
Hello Ravi!
How are you today?

Create a welcome cookie

<%
dim numvisits
response.cookies("NumVisits").Expires=date+365
numvisits=request.cookies("NumVisits")

if numvisits="" then
response.cookies("NumVisits")=1
response.write("Welcome! This is the first time you are visiting this Web
page.")
else
response.cookies("NumVisits")=numvisits+1
response.write("You have visited this ")
response.write("Web page " & numvisits)
if numvisits=1 then
response.write " time before!"
else
response.write " times before!"
end if
end if
%>
<html>
<body>
</body>
</html>

O/P:

Welcome! This is the first time you are visiting this Web page.

Login Form Using Form Collection

<% strFileTitle ="Login Using Form"%>


<%ifLCase<(Request.QueryString("PageView")) = "execute"then%>
<%ShowHeader strFileTitle%>
<%if Request.Form.Count = 0 then%>
<FORM method=post>
<TABLE WIDTH=75% BORDER=1 CELLSPACING=1 CELLPADDING=1>
<TR><TD ALIGN=texttop>
User Name: </TD><TD ALIGN=texttop>
<INPUT type="text" id=UserName name=UserName>
</TD></TR>
<TR><TD ALIGN=texttop>
Password </TD><TD ALIGN=texttop>
<INPUT type=quot;password" id=password name=password>
</TD></TR>
<TR><TD ALIGN=texttop>

</TD><TD ALIGN=texttop>
<INPUT type="submit" value="Submit"id=submit1 name=submit1>
<INPUT type="reset"value="Reset" id=reset1 name=reset1>
</TD></TR>
</TABLE>
</FORM> <%else%>
Your Username was:<%=Request.Form("UserName"%><BR>
Your Password was: <%=Request.Form("password")%><BR>
<%endif%>
<%ShowFooter%>

O/P:

rabi
User Name:

Password

Submit Reset

Your Username was: rabi


Your Password was: rabi

Application Object
An application may be a group of ASP files on the Web. To achieve some ourpose
group of ASP file work together. In ASP ,The Application object is used to tie these
files together.
To store and access variables from any page, just like the Session object,the
Application object is used. The difference is while with Sessions there is one Session
object for EACH user but there is one Application object for ALL users that can be
shared.
In a particular application (like database connection information),the Application
object should hold information that will be used by many pages . This means it is
possible access the information from any page. In an Application object , you can
change the information in one place and the changes will automatically be reflected
on all pages.
The Application object's collections, methods, and events are described below:

Collections:

Collection Description

Contains all the items appended to the application through a


Contents
script command

StaticObject Contains all the objects appended to the application with the
s HTML <object> tag

Methods

Method Description

Contents.Remove Deletes an item from the Contents collection

Contents.RemoveAll(
Deletes all items from the Contents collection
)

Prevents other users from modifying the variables in the


Lock
Application object

Enables other users to modify the variables in the


Unlock Application object (after it has been locked using the Lock
method)

Events

Event Description

Occurs when all user sessions are over, and the application
Application_OnEnd
ends

Application_OnStar Occurs before the first new session is created (when the
t Application object is first referenced)

Visit Counter Using Application Object

<%@ Language=VBScript%>
<% strFileTitle = "Visit Counter"%>
<% ifLCaseRequest.QueryString("PageView")) = "execute"then%>
<%Dim strDocumentTitle
'The document ID is a compination of the Catagory and document number
'This is to ease administration
<%strDocumentTitle = "Application Variable" %>
<%ShowHeader strFileTitle%>
<
%ifApplication("SimpleApplicationVisitor"""thenApplication("SimpleApplicationVi
sitor" = 0%>
<%=Application("SimpleApplicationVisitor"%> people have viewed this page
since
<% Response.Write Application("StartTime") & " on " Response.Write
Application("StartDate") %>
<%Application("SimpleApplicationVisitor") =
Application("SimpleApplicationVisitor") + 1%>
<%ShowFooter%>

O/P:

0 people have viewed this page since on

Session Object

Session is like when you are working with an application, you open it, do some
changes and then you close it. The computer knows who you are. It knows when
you start the application and when you end. But on the internet there is one
problem: the HTTP address doesn't maintain state so that the web server does not
know who you are and what you do.
By creating a unique cookie for each user,ASP solves this problem . The cookie is
sent to the client and it contains information that identifies the user. This interface
is called the Session object.
For a user session,the Session object is used to store information about, or
change settings . Session object is a variable that holds information about one
single user, and are available to all pages in one application. Common information
stored in session variables are name, id, and preferences. The server creates a
new Session object for each new user, and destroys the Session object when the
session expires
The Session object's collections, properties, methods, and events are described
below:

Collections:

Collection Description
Contains all the items appended to the session through a script
Contents
command

StaticObject Contains all the objects appended to the session with the HTML
s <object> tag

Properties

Property Description

Specifies the character set that will be used when displaying dynamic
CodePage
content

Sets or returns an integer that specifies a location or region.


LCID Contents like date, time, and currency will be displayed according to
that location or region

SessionI Returns a unique id for each user. The unique id is generated by the
D server

Sets or returns the timeout period (in minutes) for the Session object
Timeout
in this application

Methods

Method Description

Abandon Destroys a user session

Contents.Remove Deletes an item from the Contents collection

Contents.RemoveAll() Deletes all items from the Contents collection

Events

Event Description

Session_OnEnd Occurs when a session ends

Session_OnStart Occurs when a session starts

Returns the sessionID which is unique to the particular object Using


Application Object

<html>
<body>

<%
Response.Write(Session.SessionID)
%>

</body>
</html>

Server Object

To access properties and methods on the server, the ASP Server object is used.
Its properties and methods are described below:

Properties

Property Description

ScriptTimeou Sets or returns the maximum number of seconds a script can run
t before it is terminated

Methods

Method Description

CreateObject Creates an instance of an object

Execute Executes an ASP file from inside another ASP file

GetLastError( Returns an ASPError object that describes the error condition


) that occurred/p>

HTMLEncode Applies HTML encoding to a specified string

MapPath Maps a specified path to a physical path

Sends (transfers) all the information created in one ASP file to a


Transfer
second ASP file

URLEncode Applies URL encoding rules to a specified string

Check when this file was last modified


html>
<body>

<%
Set fs = Server.CreateObject("Scripting.FileSystemObject")
Set rs = fs.GetFile(Server.MapPath("demo_lastmodified.asp"))
modified = rs.DateLastModified
%>
This file was last modified on: <%response.write(modified)
Set rs = Nothing
Set fs = Nothing
%>

</body>
</html>

The ASPError Object

In ASP 3.0,the ASPError object was implemented and is available in IIS5 and
later.
In an ASP page,the ASPError object is used to display detailed information of any
error that occurs in scripts . When Server.GetLastError is called, the ASPError
object is created so the error information can only be accessed by using the
Server.GetLastError method.
The ASPError object's properties are described below (all properties are read-
only):
Note:Using Server.GetLastError() method,the properties below can only be
accessed

Properties

Property Description

ASPCode Returns an error code generated by IIS

ASPDescriptio Returns a detailed description of the error (if the error is ASP-
n related)

Returns the source of the error (was the error generated by


Category
ASP? By a scripting language? By an object?)

Returns the column position within the file that generated the
Column
error
Description Returns a short description of the error

File Returns the name of the ASP file that generated the error

Line Returns the line number where the error was detected

Number Returns the standard COM error code for the error

Returns the actual source code of the line where the error
Source
occurred

ASP AdRotator Component

You can create an AdRotator object using the ASP AdRotator component that
displays a different image each time a user enters or refreshes a page. A text file
includes information about the images..

Syntax

<%
set adrotator=server.createobject("MSWC.AdRotator")
adrotator.GetAdvertisement("textfile.txt")
%>

Example
Assume we have a file called "TopBanners.asp". It looks like this:

<html>
<body>
<%
set adrotator=Server.CreateObject("MSWC.AdRotator")
response.write(adrotator.GetAdvertisement("ads.txt"))
%>
</body>
</html>

The file "ads.txt" looks like this:

*
learnASP.jpg
http://www.ebooks.univdatabase.com/
Visit Academictutorials
80
vyom.gif
http://www.vyom.co.in/
Visit Vyom
20

The lines below the asterisk in the file "ads.txt" specifies the images to be
displayed, the hyperlink addresses, the alternate text (for the images), and the
display rates in percent of the hits. We see that the academictutorials image will
be displayed for 80 % of the hits and the vyom image will be displayed for 20 %
of the hits in the text file above.
Note: To get the links to work when a user clicks on them, we will have to modify
the file "ads.txt" a bit:

REDIRECT TopBanners.asp
*
learnASP.gif
http://www.ebooks.univdatabase.com/
Visit Academictutorials
80
vyom.gif
http://www.vyom.co.in/
Visit Vyom
20

To redirect,the redirection page (banners.asp) will now receive a querystring with


a variable named URL containing the URL.
Note: you can insert the following lines under REDIRECT to specify the height,
width, and border of the image:

REDIRECT Topbanners.asp
WIDTH 468
HEIGHT 60
BORDER 0
*
learnASP.gif
...
...

The last thing to do is to add some lines of code to the "Topbanners.asp" file:

<%
url=Request.QueryString("url")
If url<>"" then Response.Redirect(url)
%>
<html>
<body>
<%
set adrotator=Server.CreateObject("MSWC.AdRotator")
response.write(adrotator.GetAdvertisement("textfile.txt"))
%>
</body>
</html>

Properties

Property Description Example

<%
Specifies the set
size of the adrot=Server.CreateObject("MSWC.AdRotator")
Border borders around adrot.Border="2"
the Response.Write(adrot.GetAdvertisement("ads.txt")
advertisement )
%>

<%
set
Specifies
adrot=Server.CreateObject("MSWC.AdRotator")
whether the
Clickable adrot.Clickable=false
advertisement
Response.Write(adrot.GetAdvertisement("ads.txt")
is a hyperlink
)
%>

<%
set
Name of the
adrot=Server.CreateObject("MSWC.AdRotator")
TargetFram frame to
adrot.TargetFrame="target='_blank'"
e display the
Response.Write(adrot.GetAdvertisement("ads.txt")
advertisement
)
%>

Methods

Method Description Example

Returns
<%
HTML that
GetAdvertiseme Response.Write(adrot.GetAdvertisement("ads.tx
displays the
n t"))
advertisemen
%>
t in the page

Das könnte Ihnen auch gefallen