Sei sulla pagina 1di 54

Distributed by--

--Praful aka Search Engine

Web Technology Notes

(For Private Circulation Only)


KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

Introduction to ASP
An ASP file can contain text, HTML tags and scripts. Scripts in an ASP file are
executed on the server

What you should already know


Before you continue you should have some basic understanding of the following:

• HTML / XHTML
• A scripting language like JavaScript or VBScript

What is ASP?
• ASP stands for Active Server Pages
• ASP is a program that runs inside IIS
• IIS stands for Internet Information Services
• IIS comes as a free component with Windows 2000
• IIS is also a part of the Windows NT 4.0 Option Pack
• The Option Pack can be downloaded from Microsoft
• PWS is a smaller - but fully functional - version of IIS
• PWS can be found on your Windows 95/98 CD

ASP Compatibility
• ASP is a Microsoft Technology
• To run IIS you must have Windows NT 4.0 or later
• To run PWS you must have Windows 95 or later
• ChiliASP is a technology that runs ASP without Windows OS
• InstantASP is another technology that runs ASP without Windows

What is an ASP File?


• An ASP file is just the same as an HTML file
• An ASP file can contain text, HTML, XML, and scripts
• Scripts in an ASP file are executed on the server
• An ASP file has the file extension ".asp"

How Does ASP Differ from HTML?


• When a browser requests an HTML file, the server returns the file
• When a browser requests an ASP file, IIS passes the request to the ASP
engine. The ASP engine reads the ASP file, line by line, and executes the

10:36 AM 1 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

scripts in the file. Finally, the ASP file is returned to the browser as plain
HTML

What can ASP do for you?


• Dynamically edit, change or add any content of a Web page
• Respond to user queries or data submitted from HTML forms
• Access any data or databases and return the results to a browser
• Customize a Web page to make it more useful for individual users
• The advantages of using ASP instead of CGI and Perl, are those of
simplicity and speed
• Provide security since your ASP code can not be viewed from the browser
• Clever ASP programming can minimize the network traffic

Important: Because the scripts are executed on the server, the browser that
displays the ASP file does not need to support scripting at all!

ASP Syntax
You cannot view the ASP source code by selecting "View source" in a browser,
you will only see the output from the ASP file, which is plain HTML. This is
because the scripts are executed on the server before the result is sent back to the
browser.

In our ASP tutorial, every example displays the hidden ASP source code. This
will make it easier for you to understand how it works.

Examples
Write text with ASP
How to write some text with ASP.

10:36 AM 2 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

Add some HTML to the text


How to format the text with HTML tags.

10:36 AM 3 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

The Basic Syntax Rule


An ASP file normally contains HTML tags, just like an HTML file. However, an
ASP file can also contain server scripts, surrounded by the delimiters <% and
%>. Server scripts are executed on the server, and can contain any expressions,
statements, procedures, or operators valid for the scripting language you prefer to
use.

Write Output to a Browser


The response.write command is used to write output to a browser. The following
example sends the text "Hello World" to the browser:

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

There is also a shorthand method for the response.write command. The following
example also sends the text "Hello World" to the browser:

<html>
<body>
<%="Hello World!"%>
</body>
</html>

VBScript
You can use several scripting languages in ASP. However, the default scripting
language is VBScript:

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

The example above writes "Hello World!" into the body of the document.

10:36 AM 4 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

JavaScript
To set JavaScript as the default scripting language for a particular page you must
insert a language specification at the top of the page:

<%@ language="javascript"%>
<html>
<body>
<%
Response.Write("Hello World!")
%>
</body>
</html>

Note: Unlike VBScript - JavaScript is case sensitive. You will have to write your
ASP code with uppercase letters and lowercase letters when the language requires
it.

Other Scripting Languages


ASP is shipped with VBScript and JScript (Microsoft's implementation of
JavaScript). If you want to script in another language, like PERL, REXX, or
Python, you will have to install script engines for them.

Important: Because the scripts are executed on the server, the browser that
displays the ASP file does not need to support scripting at all!

ASP Variables
A variable is used to store information.

If the variable is declared outside a procedure it can be changed by any script in


the ASP file. If the variable is declared inside a procedure, it is created and
destroyed every time the procedure is executed.

Examples
Declare a variable
Variables are used to store information. This example demonstrates how to
declare a variable, assign a value to it, and use the value in a text.

10:36 AM 5 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

Declare an array
Arrays are used to store a series of related data items. This example demonstrates
how to declare an array that stores names.

10:36 AM 6 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

Loop through the HTML headers


How to loop through the six headers in HTML.

10:36 AM 7 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

Time-based greeting using VBScript


This example will display a different message to the user depending on the time
on the server.

Time-based greeting using JavaScript


This example is the same as the one above, but the syntax is different.

10:36 AM 8 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

Lifetime of Variables
A variable declared outside a procedure can be accessed and changed by any
script in the ASP file.

A variable declared inside a procedure is created and destroyed every time the
procedure is executed. No scripts outside the procedure can access or change the
variable.

To declare variables accessible to more than one ASP file, declare them as session
variables or application variables.

Session Variables

Session variables are used to store information about ONE single user, and are
available to all pages in one application. Typically information stored in session
variables are name, id, and preferences.

Application Variables

Application variables are also available to all pages in one application.


Application variables are used to store information about ALL users in a specific
application.

10:36 AM 9 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

ASP Procedures

In ASP you can call a JavaScript procedure from a VBScript and vice versa.

Examples
Call a procedure using VBScript
How to call a VBScript procedure from ASP.

Call a procedure using JavaScript


How to call a JavaScript procedure from ASP.

10:36 AM 10 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

Call procedures using VBScript


How to call both a JavaScript procedure and a VBScript procedure in an ASP file.

10:36 AM 11 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

Procedures
The ASP source code can contain procedures and functions:

<html>
<head>
<%
sub vbproc(num1,num2)
response.write(num1*num2)
end sub
%>
</head>
<body>
<p>Result: <%call vbproc(3,4)%></p>
</body>
</html>

Insert the <%@ language="language" %> line above the <html> tag to write
procedures or functions in another scripting language than default:

<%@ language="javascript" %>


<html>
<head>
<%
function jsproc(num1,num2)
{
Response.Write(num1*num2)
}
%>
</head>
<body>
<p>Result: <%jsproc(3,4)%></p>
</body>
</html>

Differences Between VBScript and JavaScript


When calling a VBScript or a JavaScript procedure from an ASP file written in
VBScript, you can use the "call" keyword followed by the procedure name. If a
procedure requires parameters, the parameter list must be enclosed in parentheses
when using the "call" keyword. If you omit the "call" keyword, the parameter list
must not be enclosed in parentheses. If the procedure has no parameters, the
parentheses are optional.

When calling a JavaScript or a VBScript procedure from an ASP file written in


JavaScript, always use parentheses after the procedure name.

10:36 AM 12 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

ASP Forms and User Input


The Request.QueryString and Request.Form commands may be used to retrieve
information from forms, like user input.

Examples
A form with method="get"
How to interact with the user, with the Request.QueryString command.

A form with method="post"


How to interact with the user, with the Request.Form command.

10:36 AM 13 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

A form with radio buttons


How to interact with the user, through radio buttons, with the Request.Form
command.

10:36 AM 14 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

User Input
The Request object may be used to retrieve user information from forms.

Form example:

<form method="get" action="simpleform.asp">


First Name: <input type="text" name="fname" />
<br />
Last Name: <input type="text" name="lname" />
<br /><br />
<input type="submit" value="Submit" />
</form>

User input can be retrieved in two ways: With Request.QueryString or


Request.Form.

Request.QueryString
The Request.QueryString command is used to collect values in a form with
method="get". Information sent from a form with the GET method is visible to
everyone (it will be displayed in the browser's address bar) and has limits on the
amount of information to send.

10:36 AM 15 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

If a user typed "Bill" and "Gates" in the form example above, the URL sent to the
server would look like this:

http://www.w3schools.com/simpleform.asp?fname=Bill&lname=Gates

Assume that the ASP file "simpleform.asp" contains the following script:

<body>
Welcome
<%
response.write(request.querystring("fname"))
response.write(" " & request.querystring("lname"))
%>
</body>

The browser will display the following in the body of the document:

Welcome Bill Gates

Request.Form
The Request.Form command is used to collect values in a form with
method="post". Information sent from a form with the POST method is invisible
to others and has no limits on the amount of information to send.

If a user typed "Bill" and "Gates" in the form example above, the URL sent to the
server would look like this:

http://www.w3schools.com/simpleform.asp

Assume that the ASP file "simpleform.asp" contains the following script:

<body>
Welcome
<%
response.write(request.form("fname"))
response.write(" " & request.form("lname"))
%>
</body>

The browser will display the following in the body of the document:

Welcome Bill Gates

10:36 AM 16 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

Form Validation
User input should be validated on the browser whenever possible (by client
scripts). Browser validation is faster and you reduce the server load.

You should consider using server validation if the user input will be inserted into
a database. A good way to validate a form on the server is to post the form to
itself, instead of jumping to a different page. The user will then get the error
messages on the same page as the form. This makes it easier to discover the error.

ASP Cookies
A cookie is often used to identify a user.

Examples
Welcome cookie
How to create a Welcome cookie.

10:36 AM 17 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

What is a Cookie?
A cookie is often used to identify a user. A cookie is a small file that the server
embeds on the user's computer. Each time the same computer requests a page
with a browser, it will send the cookie too. With ASP, you can both create and
retrieve cookie values.

How to Create a Cookie?


The "Response.Cookies" command is used to create cookies.

Note: The Response.Cookies command must appear BEFORE the <html> tag.

In the example below, we will create a cookie named "firstname" and assign the
value "Alex" to it:

<%
Response.Cookies("firstname")="Alex"
%>

It is also possible to assign properties to a cookie, like setting a date when the
cookie should expire:

<%
Response.Cookies("firstname")="Alex"
Response.Cookies("firstname").Expires=#May 10,2002#
%>

How to Retrieve a Cookie Value?


The "Request.Cookies" command is used to retrieve a cookie value.

In the example below, we retrieve the value of the cookie named "firstname" and
display it on a page:

<%
fname=Request.Cookies("firstname")
response.write("Firstname=" & fname)
%>

Output:

Firstname=Alex

10:36 AM 18 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

A Cookie with Keys


If a cookie contains a collection of multiple values, we say that the cookie has
Keys.

In the example below, we will create a cookie collection named "user". The "user"
cookie has Keys that contains information about a user:

<%
Response.Cookies("user")("firstname")="John"
Response.Cookies("user")("lastname")="Smith"
Response.Cookies("user")("country")="Norway"
Response.Cookies("user")("age")="25"
%>

Read all Cookies


Look at the following code:

<%
Response.Cookies("firstname")="Alex"
Response.Cookies("user")("firstname")="John"
Response.Cookies("user")("lastname")="Smith"
Response.Cookies("user")("country")="Norway"
Response.Cookies("user")("age")="25"
%>

Assume that your server has sent all the cookies above to a user.

Now we want to read all the cookies sent to a user. The example below shows
how to do it (note that the code below checks if a cookie has Keys with the
HasKeys property):

<html>
<body>
<%
dim x,y
for each x in Request.Cookies
response.write("<p>")
if Request.Cookies(x).HasKeys then
for each y in Request.Cookies(x)
response.write(x & ":" & y & "=" & Request.Cookies(x)(y))
response.write("<br />")
next
else
Response.Write(x & "=" & Request.Cookies(x) & "<br />")
end if
response.write "</p>"
next
%>

10:36 AM 19 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

</body>
</html>

Output:

firstname=Alex

user:firstname=John
user:lastname=Smith
user:country=Norway
user:age=25

What if a Browser Does NOT Support Cookies?


If your application deals with browsers that do not support cookies, you will have
to use other methods to pass information from one page to another in your
application. There are two ways of doing this:

1. Add parameters to a URL

You can add parameters to a URL:

<a href="welcome.asp?fname=John&lname=Smith">
Go to Welcome Page</a>

And retrieve the values in the "welcome.asp" file like this:

<%
fname=Request.querystring("fname")
lname=Request.querystring("lname")
response.write("<p>Hello " & fname & " " & lname & "!</p>")
response.write("<p>Welcome to my Web site!</p>")
%>

2. Use a form

You can use a form. The form passes the user input to "welcome.asp" when the
user clicks on the Submit button:

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


First Name: <input type="text" name="fname" value="">
Last Name: <input type="text" name="lname" value="">
<input type="submit" value="Submit">
</form>

Retrieve the values in the "welcome.asp" file like this:

<%

10:36 AM 20 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

fname=Request.form("fname")
lname=Request.form("lname")
response.write("<p>Hello " & fname & " " & lname & "!</p>")
response.write("<p>Welcome to my Web site!</p>")
%>

ASP Session Object


The Session object is used to store information about, or change settings for a user
session. Variables stored in the Session object hold information about one single
user, and are available to all pages in one application.

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 web server does not know who you are and what you do
because the HTTP address doesn't maintain state.

ASP solves this problem by creating a unique cookie for each user. The cookie is
sent to the client and it contains information that identifies the user. This interface
is called the Session object.

The Session object is used to store information about, or change settings for a user
session. Variables stored in the Session object hold 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:

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

When does a Session End?


A session ends if a user has not requested or refreshed a page in the application
for a specified period. By default, this is 20 minutes.

10:36 AM 21 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

If you want to set a timeout interval that is shorter or longer than the default, you
can set the Timeout property.

The example below sets a timeout interval of 5 minutes:

<%
Session.Timeout=5
%>

To end a session immediately, you may use the Abandon method:

<%
Session.Abandon
%>

Note: The main problem with sessions is WHEN they should end. We do not
know if the user's last request was the final one or not. So we do not know how
long we should keep the session "alive". Waiting too long for an idle session uses
up resources on the server, but if the session is deleted too soon the user has to
start all over again because the server has deleted all the information. 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


The most important thing about the Session object is that you can store variables
in it.

The example below will set the Session variable username to "Donald Duck" and
the Session variable age to "50":

<%
Session("username")="Donald Duck"
Session("age")=50
%>

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

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

The line above returns: "Welcome Donald Duck".

You can also store user preferences in the Session object, and then access that
preference to choose what page to return to the user.

10:36 AM 22 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

The example below specifies a text-only version of the page if the user has a low
screen resolution:

<%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


The Contents collection contains all session variables.

It is possible to remove a session variable with the Remove method.

The example below removes the session variable "sale" if the value of the session
variable "age" is lower than 18:

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

To remove all variables in a session, use the RemoveAll method:

<%
Session.Contents.RemoveAll()
%>

Loop Through the Contents Collection


The Contents collection contains all session variables. You can loop through the
Contents collection, to see what's stored in it:

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

Result:

username

10:36 AM 23 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

age

If you do not know the number of items in the Contents collection, you can use
the Count property:

<%
dim i
dim j
j=Session.Contents.Count
Response.Write("Session variables: " & j)
For i=1 to j
Response.Write(Session.Contents(i) & "<br />")
Next
%>

Result:

Session variables: 2
Donald Duck
50

Loop Through the StaticObjects Collection


You can loop through the StaticObjects collection, to see the values of all objects
stored in the Session object:

<%
dim i
For Each i in Session.StaticObjects
Response.Write(i & "<br />")
Next
%>

ASP Request Object

The ASP Request object is used to get information from the user.

Request Object
When a browser asks for a page from a server, it is called a request. The ASP
Request object is used to get information from the user. Its collections, properties,
and methods are described below:

10:36 AM 24 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

Collections-----------
COOKIE

The Cookies collection is used to set or get cookie values. If the cookie does not
exist, it will be created, and take the value that is specified.

Syntax
Response.Cookies(name)[(key)|.attribute]=value
variablename=Request.Cookies(name)[(key)|.attribute]

Parameter Description
name Required. The name of the cookie
value Required for the Response.Cookies command. The value of the
cookie
attribute Optional. Specifies information about the cookie. Can be one of
the following parameters:

• Domain - Write-only. The cookie is sent only to requests


to this domain
• Expires - Write-only. The date when the cookie expires.
If no date is specified, the cookie will expire when the
session ends
• HasKeys - Read-only. Specifies whether the cookie has
keys (This is the only attribute that can be used with the
Request.Cookies command)
• Path - Write-only. If set, the cookie is sent only to
requests to this path. If not set, the application path is
used
• Secure - Write-only. Indicates if the cookie is secure

key Optional. Specifies the key to where the value is assigned

The "Request.Cookies" command is used to get a cookie value.

In the example below, we retrieve the value of the cookie "firstname" and display
it on a page:

<%
fname=Request.Cookies("firstname")
response.write("Firstname=" & fname)
%>

Output:

Firstname=Alex

10:36 AM 25 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

A cookie can also contain a collection of multiple values. We say that the cookie
has Keys.

The code below reads all the cookies your server has sent to a user. Note that the
code checks if a cookie has Keys with the HasKeys property:

<html>
<body>
<%
dim x,y
for each x in Request.Cookies
response.write("<p>")
if Request.Cookies(x).HasKeys then
for each y in Request.Cookies(x)
response.write(x & ":" & y & "=" & Request.Cookies(x)(y))
response.write("<br /")
next
else
Response.Write(x & "=" & Request.Cookies(x) & "<br />")
end if
response.write "</p>"
next
%>
</body>
</html>
%>

Output:

firstname=Alex

user:firstname=John
user:lastname=Smith
user: country=Norway
user: age=25

Create a welcome cookie


This example demonstrates how to create a Welcome Cookie with the Cookies
Collection.

10:36 AM 26 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

Collections-----------
FORM

The Form collection is used to retrieve the values of form elements from a form
that uses the POST method.

Note: If you want to post large amounts of data (beyond 100 kb) the
Request.Form cannot be used.

Syntax
Request.Form(element)[(index)|.Count]

Parameter Description
element Required. The name of the form element from which the
collection is to retrieve values
index Optional. Specifies one of multiple values for a parameter. From
1 to Request.Form(parameter).Count.

Form Collection Examples

10:36 AM 27 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

A form collection in its simplest use


This example demonstrates how the Form collection retrieves the values from a
form. The form uses the POST method, which means that the information sent is
invisible to others, and it has no limits (you can send a large amount of
information).

How to use information from forms


This example demonstrates how to use the values retrieved from a form. We use
the Form collection. The form uses the post method.

10:36 AM 28 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

More information from a form


This example demonstrates what the Form collection contains if several input
fields have the same name. It shows how to separate input fields with equal names
from each other. It also shows how to use the Count keyword to count the "name"
property. The form uses the post method.

10:36 AM 29 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

A form with radio buttons


This example demonstrates how to interact with the user through radio buttons,
with the Form collection. The form uses the post method.

10:36 AM 30 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

A form with checkboxes


This example demonstrates how to interact with the user through checkboxes,
with the Form collection. The form uses the post method.

10:36 AM 31 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

Collections-----------
QUERYSTRING

The QueryString collection is used to retrieve the variable values in the HTTP
query string.

The HTTP query string is specified by the values following the question mark (?),
like this:

<a href= "test.asp?txt=this is a query string test">Link with a query string</a>

The line above generates a variable named txt with the value "this is a query
string test".

Query strings are also generated by form submission, or by a user typing a query
into the address bar of the browser.

Syntax
Request.QueryString(variable)[(index)|.Count]

Parameter Description

10:36 AM 32 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

variable Required. The name of the variable in the HTTP query string to
retrieve
index Optional. Specifies one of multiple values for a variable. From 1
to Request.QueryString(variable).Count

QueryString Collection Examples


Send query information when a user clicks on a link
This example demonstrates how to send some extra query information to a page
within a link, and retrieve that information on the destination page (which is, in
this example, the same page).

A QueryString collection in its simplest use


This example demonstrates how the QueryString collection retrieves the values
from a form. The form uses the GET method, which means that the information
sent is visible to everybody (in the address field). The GET method also limits the
amount of information that can be sent.

10:36 AM 33 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

10:36 AM 34 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

How to use information from forms


This example demonstrates how to use the values retrieved from a form. We use
the QueryString collection. The form uses the get method.

More information from a form


This example demonstrates what the QueryString contains if several input fields
have the same name. It shows how to separate input fields with equal names from
each other. It also shows how to use the Count keyword to count the "name"
property. The form uses the get method.

<html>

<body>

<form action="demo_reqquery2.asp" method="get">

First name:

<input type="text" name="name" value="" />

<br />

10:36 AM 35 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

Last name:

<input type="text" name="name" value="" />

<br />

<input type="submit" value="Submit" />

</form>

<hr>

</body>

</html>

10:36 AM 36 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

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

Collections-----
COOKIE

The Cookies collection is used to set or get cookie values. If the cookie does not
exist, it will be created, and take the value that is specified.

Note: The Response.Cookies command must appear before the <html> tag.

Syntax
Response.Cookies(name)[(key)|.attribute]=value
variablename=Request.Cookies(name)[(key)|.attribute]

Parameter Description
name Required. The name of the cookie
value Required for the Response.Cookies command. The value of the
cookie
attribute Optional. Specifies information about the cookie. Can be one of
the following parameters:

• Domain - Write-only. The cookie is sent only to requests


to this domain
• Expires - Write-only. The date when the cookie expires.
If no date is specified, the cookie will expire when the
session ends
• HasKeys - Read-only. Specifies whether the cookie has
keys (This is the only attribute that can be used with the
Request.Cookies command)
• Path - Write-only. If set, the cookie is sent only to
requests to this path. If not set, the application path is
used
• Secure - Write-only. Indicates if the cookie is secure

key Optional. Specifies the key to where the value is assigned

10:36 AM 37 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

Examples

The "Response.Cookies" command is used to create a cookie or to set a cookie


value:

<%
Response.Cookies("firstname")="Alex"
%>

In the code above, we have created a cookie named "firstname" and assigned the
value "Alex" to it.

It is also possible to assign some attributes to a cookie, like setting a date when a
cookie should expire:

<%
Response.Cookies("firstname")="Alex"
Response.Cookies("firstname").Expires=#May 10,2002#
%>

Now the cookie named "firstname" has the value of "Alex", and it will expire
from the user's computer at May 10, 2002.

A cookie can also contain a collection of multiple values. We say that the cookie
has Keys.

In the example below, we will create a cookie-collection named "user". The


"user" cookie has Keys that contains information about a user:

<%
Response.Cookies("user")("firstname")="John"
Response.Cookies("user")("lastname")="Smith"
Response.Cookies("user")("country")="Norway"
Response.Cookies("user")("age")="25"
%>

Output:

firstname=Alex

user:firstname=John
user:lastname=Smith
user: country=Norway
user: age=25

METHOD-----
WRITE

The Write method writes a specified string to the output.

10:36 AM 38 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

Syntax
Response.Write variant

Parameter Description
variant Required. The data to write

Examples
Write text with ASP
This example demonstrates how to write text with ASP.

<html>
<body>

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

</body>
</html>

Format text with HTML tags in ASP


This example demonstrates how to combine text and HTML tags with ASP.
<html>

10:36 AM 39 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

<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>

METHOD-----
CLEAR

The Clear method clears any buffered HTML output.

Note: This method does not clear the response headers, only the response body.

Note: If response.Buffer is false, this method will cause a run-time error.

Syntax
response.Clear

10:36 AM 40 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

Examples
<%
response.Buffer=true
%>
<html>
<body>
<p>This is some text I want to send to the user.</p>
<p>No, I changed my mind. I want to clear the text.</p>
<%
response.Clear
%>
</body>
</html>

Output:

(nothing)

10:36 AM 41 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

ASP OBJECT MODEL

Active Server Pages consist of six built in objects. They are ready made objects
which provide functionality to your web pages without requiring you to make
custom objects ( though you can if you want to, later on that topic ) . Following
are the six built in ASP objects :

• Application
• ObjectContext
• Request
• Response
• Server
• Session

The Application Object

The Application object is created when the first .asp page is requested after
starting the IIS and remains there until the server shuts down. All the variables
created with application object have application level scope meaning there by that
they are accessible to all the users. All .asp pages in a virtual directory and its

10:36 AM 42 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

subdirectories come under the application scope. So application level variables


are shared by more than one user at a time.

Syntax

Application.method
Collections Description

Contents A collection of all the items that have been


added to the Application object.
StaticObjects Collection of all the items that have been added
to the Application object through <object> tag.

Methods Description

Contents.Remove Deletes the specified item from the


Application.Contents collection.
Contents.RemoveAll Deletes all the items from the
Application.Contents collection.
Lock Locks the application object so that only one
user at a time can modify the values.
UnLock Unlocks the application object allowing other
users to modify application level variables.

Events Description

Application_OnEnd This event occurs when the IIS is shut down


after Session_OnEnd event. All the variables
are destroyed after that.
Application_OnStart This event occurs when the first .asp page is
called after starting the IIS. Application level
variables can be declared here.

The ObjectContext Object


The ObjectContext object is used to commit or abort transactions. For an .asp
page to commit transaction, @TRANSACTION directive should be present in the
script.

Syntax

ObjectContext.method

10:36 AM 43 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

Methods Description

SetAbort Aborts the transaction initiated by the ASP


script.
SetComplete Declares that there is no reason for the
transaction not to complete. So if all the
components taking part in the transaction also
call SetComplete method then the transaction
will complete.

Events Description

OnTransactionAbort This event occurs when the transaction is


aborted.
OnTransactionCommit This event occurs when the transactional
script's transaction is committed.

The Request Object


The Request object makes available all the values that client browser passes to the
server during an HTTP request. It includes client browser info, cookie details ( of
this domain only ), client certificates ( if accessing through SSL ) etc.

Syntax

Request.collection|property|method (variable)

Collections Description

ClientCertificate Makes us available a collection of values stored in the client certificate


that is sent to the HTTP request. It is usually of interest when the client
is requesting secure pages through SSL connection. But before using
this collection the server should be configured to request client
certificates.
Cookies Makes us available all the cookies stored in the client browser for this
domain.
Form Collection of all the values of Form element in the HTTP request.
QueryString Collection of variables which are stored in the HTTP query string.
Name / value pairs can also be appended to the URL after the end of
page name e.g.
"http://www.stardeveloper.com/asp_request.asp?author=Faisal+Khan"
contains one variable 'author' with a value of 'Faisal Khan'.
ServerVariables Contains a collection of predetermined environment variables plus a
collection of all the HTTP header values sent from the client browser to

10:36 AM 44 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

the server.

Properties Description

TotalBytes An integer read-only value which gives the


total number of bytes the client browser is to
the server with each request.

Methods Description

BinaryRead Retrieves data sent to the server from the client


in raw format as part of the POST request. It
saves all this data in a SafeArray.

The Response Object


The Response object is used to send the output back to the client (browser). It
includes all the HTTP variables, cookies that will be stored on the client browser
and other info about the content being sent.

Syntax

Response.collection|property|method
Collections Description

Cookies A collection used to specify the values of


cookies which will be sent back to the client
browser.

Properties Description

Buffer A boolean value indicating whether page output


is buffered or not. If the page's Response.Buffer
property is set to true then the output from the
page will not be sent to the client until all the
script in that page is processed. Note that in IIS
5, Response.Buffer is by default set to true. So
if you want to turn off buffering of your page's
output then you will have to set
Response.Buffer to false.
CacheControl A string specifying that the output from the
ASP should be cached or not. If you want proxy
server to cache the output of your ASP then set
this property to Public or if you don't want to
enable caching of your ASP then set it to
Private.

10:36 AM 45 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

Charset A string which appends the name of character


set to be used to HTTP-content-type header.
ContentType A string which specifies the HTTP content type
for the response. If Response.ContentType is
not specified then by default MIME-type
"text/html" is used.
Expires An integer specifying the duration of time in
minutes after which the page expires in the
client browser cache.
ExpiresAbsolute Date / time after which the page cached in the
client browser expires and is no longer valid
e.g. Response.ExpiresAbsolute = #March 31,
2001 12:00:00#
IsClientConnected A boolean value indicating whether the client is
still connected to this particular page. If this
property returns false then the page's script
processing can be stopped by using
Response.End method.
Pics A string which creates PICS header and then
adds it to the HTTP headers. It indicates PICS
content rating e.g. violence, sex etc.
Status A string which specifies the value of status line
of the server. It is included in HTTP headers of
the response. This string should contain both
three digit code and a brief explanation for it
e.g. "404 File Not Found".

Methods Description

AddHeader Adds a custom new HTTP header to the


response. Must be used before any text or
HTML is sent to the client. Does not replace a
HTTP header of the same name e.g.
Response.AddHeader "AUTHENTICATED",
"You are now logged on."
AppendToLog A string which is added to the end of the web
server log entry for this page e.g.
Response.AppendToLog "Your custom log
message goes here".
BinaryWrite Writes down the given information to the
current HTTP output without any character set
conversion. It is useful for writing non-string

10:36 AM 46 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

information such as binary data required by an


application or for sending bytes to make up an
image.
Clear Erases any existing HTML buffered output
from the IIS response buffer. Used to abort the
partly completed page.
End Stops the processing of the script in the current
page and sends the already created content to
the client. Further processing of the page is
aborted.
Flush Sends the buffered output immediately to the
client. It is opposite to that of Response.Clear
which erases the currently buffered content. Is
used to send parts of long pages to the client
when Response.Buffer is set to true.
Redirect Redirects the browser to another page (URL)
e.g. Response.Redirect
"http://www.stardeveloper.com".
Write Writes the specified string to the web page e.g.
Response.Write "Hello World!".

The Server Object


The Server object makes us available the methods and properties of our server (
IIS ).

Syntax

Server.property|method
Properties Description

ScriptTimeout An integer which specifies time in seconds until


which the script can run after that the server
aborts the script and displays an error message.

Methods Description

CreateObject Creates an instance of the object ( a component,


application or a scripting object ). The
component can be instantiated by giving its
CLSID or ProgID in the Server.CreateObject
method e.g. Server.CreateObject
("MSWC.MyInfo").

10:36 AM 47 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

Execute Executes the given .asp page and then returns


the control to the page who called the method.
Very useful method which can be used to
execute another .asp page without leaving the
current page and then control is passed back to
the calling page.
GetLastError Returns an ASPError object which can be used
to get information about the last error occured in
the ASP script.
HTMLEncode Provides HTML encoding to a given string. All
non-legal HTML characters are converted to
their equivalent HTML entity e.g. "<" is
converted to &lt; .
MapPath Maps the specified virtual or relative path into
physical path of the server.
Transfer Transfers the control of the page to another page
specified in the URL. Note that unlike Execute,
control of the page is not returned to the page
calling the Server.Transfer method.
URLEncode Provides URL encoding to a given string e.g.
Server.URLEncode
("http://www.stardeveloper.com") returns
http%3A%2F%2Fwww%2Estardeveloper%2Ecom.

The Session Object


The Session object is automatically created every time client browser access
pages from your web site. Session object is specific for every user and varies from
user to user. It can be used to store variables specific for a user and IIS will
maintain these variables when the client moves across pages within your site. You
can create and access Session scope variables. You can store user specific
preferences within Session object such as 'font-size, background-color' etc.

Note that scripts for different Events are to be declared in global.asa file.

Syntax

Session.collection|property|method
Collections Description

Contents Contains all the items which have been added to


the Session object. You can iterate through the
Contents collection and retrieve a list of all the
items added or you can retrieve a specific item.

10:36 AM 48 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

Note that it contains all the Session items except


the ones created using <object> element.
StaticObjects Contains all the items which have Session scope
created using <object> element. As with
Session.Contents collection you can iterate
through the StaticObjects collection to get a list
of items or you can get a specific item out of
the StaticObjects collection.

Properties Description

CodePage An integer which defines the code page to be


used to display content to the client browser e.g.
code page 1252 is used to for American english
and most European languages and 932 is used
for Japanese kanji.
LCID Stands for locale identifier. It is a standard
international abbreviation that uniquely
identifies the locale e.g. LCID 2057 stands for
British locale.
SessionID A long which returns the session identifier for
this client browser.
Timeout An integer which specifies a time out period in
minutes. If the client doesn't refresh or request
any page of your site within this time out period
then the server ends the current session. If you
do not specify any time out period then by
default time out period is 20 minutes.
Methods Description
Abandon Destroys the current session object and
releases its resources, meaning there by that if
the client requests any page of your site after
Session.Abandon method has been called then
a separate session will be started.
Contents.Remove Deletes the given item from the
Session.Contents collection.
Contents.RemoveAll Destroys all the items in the Session.Contents
collection.

Events Description

Session_OnEnd This event occurs when the session is

10:36 AM 49 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

abandoned or times out for a specific user.


Session_OnStart Occurs when a new session is started. All the
ASP objects are available for you to use. You
can define your session wide variables here.

HTTP
The Hypertext Transfer Protocol (HTTP) is the basic, underlying, application-
level protocol used to facilitate the transmission of data to and from a Web server.

HTTP provides a simple, fast way to specify the interaction between client and
server. The protocol actually defines how a client must ask for data from the
server and how the server returns it.

HTTP does not specify how the data actually is transferred; this is up to lower-
level network protocols such as TCP.

The first version of HTTP, known as version 0.9, was used as early as 1990.
HTTP version 1.0 as defined by RFC 1945, is supported by most servers and
clients (Web browsers). However, HTTP 1.0 does not properly handle the effects
of hierarchical proxies and caching, or provide features to facilitate virtual hosts.
More important, HTTP 1.0 has significant performance problems due to the
opening and closing of many connections for a single Web page.

The current version, HTTP 1.1, solves many of the past problems of the protocol.
It is supported by version 4-generation Web browsers and up.

There still are many limitations to HTTP, however. It is used increasingly in


applications that need more sophisticated features, including distributed
authoring, collaboration, multimedia support, and remote procedure calls. Various
ideas to extend HTTP have been discussed and a generic Extension Framework
for HTTP has been introduced by the W3C. Already, some facilities such as client
capability detection and privacy negotiation between browser and server have
been implemented on top of HTTP, but most of these protocols are still being
worked out. For now, HTTP continues to be fairly simple, so this discussion will
focus on HTTP 1.0 and 1.1.

HTTP Requests

The process of a Web browser or other user agentsuch as Web spider or


Robotrequesting a document from a Web (or more correctly HTTP) server is
simple, and has been discussed throughout the book. The overall process was
diagrammed in Figure .

10:36 AM 50 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

In the figure, the user first requests a document from a Web server by specifying
the URL of the document desired. During this step, a domain name lookup may
occur, which translates a machine name such as www.democompany.com to an
underlying IP address such as 206.251.142.3. If the domain name lookup fails, an
error message such as "No Such Host" or "The server does not have a DNS entry"
will be returned. Certain assumptions, such as the default service port to access
for HTTP requests (80), also might be made. This is transparent to the user, who
simply uses a URL to access a page. Once the server has been located, the
browser forms the proper HTTP request and sends the request to the server
residing at the address specified by the URL. A typical HTTP request consists of
the following:

HTTP-Method Identifier HTTP-version


<Optional additional request headers>

In this example, the HTTP-Method would be GET or POST. An identifier might


correspond to the file, and the HTTP-version indicates the dialect of HTTP being
used, such as HTTP/1.0.

People often ask why the complete URL is not shown in the request. It isn't
necessary in most cases, except when using a proxy server. The use of a relative
URL in the header is adequate. The server knows where it is; it just needs to know
what document to get from its own file tree. In the case of using a proxy server,
which requests a document on behalf of a browser, a full URL is passed to it that
later is made relative by the proxy. Aside from the simple GET method, there are
various other methods specified in HTTP. Not all are commonly used. Table
provides a summary of the HTTP 1.1 request methods.

10:36 AM 51 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

Table : Summary of HTTP 1.1 Request Methods


Method Description
GET Returns the object specified by the identifier. Notice that it also is
one of the values of the method attribute for the form element.
HEAD Returns information about the object specified by the identifier,
such as last modification data, but does not return the actual
object.
OPTIONS Returns information about the capabilities supported by a server
if no location is specified, or the possible methods that can be
applied to the specified object.
POST Sends information to the address indicated by the identifier;
generally used to transmit information from a form using the
method="POST" attribute of the form element to a server-based
CGI program.
PUT Sends data to the server and writes it to the address specified by
the identifier overwriting previous content, in basic form. This
method can be used for file upload.
DELETE Removes the file specified by the identifier; generally disallowed
for security reasons.
TRACE Provides diagnostic information by allowing the client to see
what is being received on the server.

It is interesting to note that two of the methods (GET and POST) supported by
HTTP are the values of the form element's method attribute.

• In the case of GET, it is passed through the URL because another page
is simply being fetched, as a normal GET request would do.

A GET request asks the server to “get” a piece of information, typically a


document, and return it to the client. If the request includes any additional
information, these are appended as arguments to the URL

• In the case of a POST value, the data of the form is passed behind the
scenes to the server program that should return a result page to the
browser as well.

A POST request, on the other hand, provides the server with information to be
“posted” to the URL; typically, it’s used to send the contents of an HTML form to
the server, or to provide the server with information that’s needed for back-end
processing. The information itself is contained in the body of the request.

10:36 AM 52 11/23/2007
KAUSTUBH KUSHTE a.k.a. MEAN_MACHINE

GET Versus POST


• GET can be used to retrieve any document, POST cannot.

• On the other hand, both GET and POST can be used to pass data to the
object indicated by the URL. When GET is used for this purpose, the data
is included in the URL as the argument string; in order to extract this data
with Win-CGI,you have to parse the argument string.

• When POST is used, the data is passed to the server in the body of the
request message. So, in cases in which data is sent to the server, GET and
POST differ in the method used to transmit that data.

Form Submission

A user enters input into the fields of a form. When the form is submitted, the
data contained in each field of the form is transferred to the server, which then
passes it to ASP.

This data is sent in the format name=value, where name is the name
assigned to the field by the NAME= attribute of the <INPUT> tag, and value is
the value entered in that field.

For example, if the user enters “Archie” in a field prompting for his first name,
the browser may send along the string first_name=Archie.
If the form is written to use METHOD=GET, the form data is appended to the
URL as an argument string. If the form contains many fields or if fields contain
long strings of text, the complete URL can become very large and unwieldy. In
addition, the limit of the number of characters submitted in a GET—typically
about 2000—ismuch lower than in a POST.

If the form instead uses METHOD=POST, the name=value pairs are sent as the
body of the request instead of being appended to the URL. In addition to the
greater ease of handling of POST requests, most servers offer better performance
when extracting data from the body of a request than from a URL in the request
header.

Always use the POST method with forms that change something or cause ay
irreversible action (most do). POST is safer and more efficient; GET
should never be used to change anything.

In developing your ASP scripts, you can decide whether


you want to support data passed to your program using the GET method.

10:36 AM 53 11/23/2007

Potrebbero piacerti anche