Vous êtes sur la page 1sur 38

Introduction To ASP

What is an ASP File? ASP is the acronym for Active Server Pages File extension: .asp text/html TEXT public.html Microsoft Technology ASP.NET ASP 3.0 ASP is a specification for a dynamically created MIME type: Web page Type code: An ASP file contains text, HTML, XML, and Uniform Type scripts also. Identifier: An ASP file must have an .asp file extension Developed by: An ASP file can be created using a simple text editor Type of format: Extended to: Standard(s): ASP is a program that will run inside IIS or PWS. Scripts in an ASP file are executed on the server only.

What Is ASP? (Active Server Page) A Web server technology that allows for the creation of dynamic, interactive sessions with the user. An ASP is a Web page that contains HTML code and embedded programming code written in VBScript or Jscript. It was introduced with Version 3.0 of Microsoft's Internet Information Server . When Internet Information Server encounters an ASP page requested by the browser, it executes the embedded program. ASPs are Microsoft's alternative to CGI scripts and JavaServer Pages (JSPs), which allow Web pages to interact with databases and other programs. Third- party products add ASP capability to non-Microsoft Web servers. The Active Server Page technology is an ISAPI program and ASP documents use an .ASP extension. Creating an ASP Document Creating an ASP document is easy. To begin coding ASP you need only two things: a simple-text editor like notepad or Textpad or Editplus and the dedication to follow our tutorial! Notepad is the most basic of simple-text editors and you will probably code a fair amount of HTML with it. When a browser requests an ASP file, IIS passes the request file to the ASP engine. The ASP engine reads the corresponding ASP file, line by line, and executes the scripts in the file. Finally, the ASP file is returned to the browser as plain HTML format. ASP can connect to databases, dynamically format the page, execute statements, and

much more. You may use VBScript, JavaScript, PerlScript, and PythonScript within Active Server Pages, with VBScript set as the default scripting language. We recommend that you use VBScript as this should do everything you need and is the most commonly used. The appearance of an Active Server Page depends on what is viewing it. An Active Server Page looks just like a normal HTML page to the Web browser that receives it. If a visitor to your Web site views the source code of an Active Server Page, that's what they see: a normal HTML page. However, the file located in the server looks very different. You also see server-side scripts. This is what the Active Server Page looks like to the Web server before it is processed and sent in response to a request. The Most Common Mistake You can insert server-side scripts anywhere in your Web page--even inside HTML tags.ASP script must be enclosed in <% and %> Quick example: <html> <body> <% response.write("Hello World!") %> </body> </html> Frequently Asked Questions What is ASP? Active Server Pages: Active Server Pages (ASP) is a server side scripting language that lets a webmaster transform the plain, static web site into dynamic solution. With Microsoft's server side scripting language you can gather data from your site's visitors, use sessions, cookies, application variables, and more. Is ASP complete solution? While ASP is useful, it is not a stand alone solution. Rather, ASP is a supplement to HTML (and CSS and even Javascript) and your final ASP code will often contain bits of pieces of code that are not ASP. If you had ever wanted to take orders, gather emails, or make a decent guestbook, ASP will provide you the necessary tools to complete these tasks. Does my computer have to run Windows? What about a Mac? You allcan do your training on a non-Windows computer like Mac. But some of the examples in our advanced classes require a newer version of Windows, like Windows 98 or Windows 2000. What you need to know? Before you start in on Academic ASP Tutorial, it is recommended that you have a some knowledge of HTML, as this tutorial will not explain the HTML code in any great depth. If your HTML knowledge could use a touchup, check out our HTML Tutorial or for the complete HTML Beginner: First Web Site Walkthrough. This ASP Tutorial is quite long, so do not try to take it on all at once. We find that reading a couple lessons at one sitting and then giving yourself time to reflect on what you 2

learned really helps to understand the subject better. Good luck! After I have edited an ASP file, I cannot view the result in my browser. Why? Make sure that you have saved the file with a proper name and extension like "C:\Inetpub\wwwroot\mypage.asp". Also make sure that you use the same file name when you open the file in your browser.It should be like localhost/mypage.asp

ASP Programming-VBScript In ASP, VBScript is the default language. VBScript is similar to Javascript, a client side programming language used to add functionality through the <script> tag. VBScript in Server side Scripting VBScript used to program ASP converts it to server side scripting. Any given web page could be created from a combination of server side and client side scripting. The confusing part is this: You must use these client side scripting languages (Javascript, VBScript, etc) to program in ASP! Server Side ASP Code using VBScript: <html> <body> <% Dim myString myString = Date() Response.Write("The date is: " & myString) %> </body> </html> O/P: The date is: 10/26/2006 Note: If you know VBScript or Visual Basic programming then you know Dim as Dimension, which is used to give "dimension" to variables. It is a good programming practice to "dimension" all your variables before you use them, as we did with myString in the above example. VBScript and JavaScript in client side Scripting Now that we have our ASP Code working, say that we wanted to use our ASP code along with some client side Javascript code. We are just going to use the Javascript write function and have our ASP Code fill in the Date. All the Javascript client code is in the default color, but ASP Server Side Code is in Red. <script> document.write("The date is:<% Dim myString 3

myString = Date() Response.Write(myString) %>") </script> O/P: The date is: 10/26/2006 Programming ASP with VBScript You should be able to follow along with our ASP tutorial with little or no VBScript knowledge, but just in case you want to know more or find some of the VBScript syntax or code confusing then you can check out our VBScript Tutorial Programming ASP in Javascript VBScript is the default scripting language that ASP is coded in, so if you want to specify a different scripting language you have to state which scripting language you will be using at the very beginning of your code. Below is the line of code that must be your first line of ASP code or else your page will break and you'll get a boring error message ASP Code: <%@ Language="javascript" 'The rest of your ASP Code....%>

Declaring Variables in ASP

ASP is not a programming language. To program in ASP you actually need to know the VBScript, the scripting language. All VBScript variable rules can be applied to your ASP code. This lesson will teach you the basics of ASP Variables and some good programming conventions.

A variable is always used to store information. In the ASP file, if the variable is declared outside a procedure it can be changed by any script. If you are declaring a variable inside a procedure, it can be reated and destroyed every time the procedure is executed.

Declaring a Variable in ASP

Always declare all your variables before you use them, even though it is not

required. Nearly all programming languages require you to declare variables so that it will increase your program's readability. In ASP you declare a variable with the use of the Dim keyword, which means Dimension. Dimension refers to the amount of space something takes up in the real world, but in computer terms it refers to space in computer memory. Variables can be declared all at once or one at a time . Below is an example of both methods

ASP Code: <% 'Single Variable Declarations Dim myVar1 Dim myVar2 'Multiple Variable Declarations Dim myVar6, myVar7, myVar8 %>

ASP Variable Naming Conventions

Default language for ASP is VBScript and so it also uses VBScripts variable naming conventions. These rules are: 1. Variable name must start with an alphabetic character (A through Z or a through z) 2. Variables cannot contain a period 3. Variables cannot be longer than 255 characters 4. Variables must be unique in the scope in which it is declared.

ASP - Assigning Values to ASP Variables You can assign values in ASP using equals "=" operator. Below we have set a variable equal to a number and a separate variable equal to a string. ASP Code: <% 'Single Variable Declarations

Dim myString, myNum, myGarbage myNum = 25 myString = "Hello" myGarbage = 99 myGarbage = "I changed my variable" Response.Write("myNum = " & myNum & "<br />") Response.Write("myString = " & myString & "<br />") Response.Write("myGarbage = " & myGarbage & "<br />") %> O/P: myNum = 25 myString = Hello myGarbage = I changed my variable

ASP Code: <html> <body> <% dim name name="Albert Einstein" response.write("My name is: " & name) %> </body> </html> O/P: My name is: Albert Einstein

Declaring an array in ASP In the example below I have taken an array "Myarray(7)" which can store seven elements. Then I have used a for loop to display all the elements. ASP Code: <html> <body> <% Dim Myarray(6),i Myarray(1) = "Albert Einstein" Myarray(2) = "Mother Teresa" Myarray(3) = "Bill Gates" Myarray(4) = "Martin Luther King Jr"

Myarray(5) = "Michale" Myarray(6) = "John" Myarray(7) = "Charles " For i = 1 to 7 response.write(Myarray(i) & "<br />") Next %> </body> </html> O/P: Albert Einstein Mother Teresa Bill Gates Martin Luther King Jr Michale John Charles

Defining an Array in ASP


In ASP, arrays follow the exact same form and rules as those arrays in VBScript. You can create an array of dynamic sized array or you can create a specific size Declaring an Fixed Size Array in ASP ASP Code: <% Dim myFixedArray(3) 'Fixed size array Dim myDynArray() 'Dynamic size array %>

Assigning Value to an Fixed Size Array Let's fill up our fixed size array with values. Our fixed array is going to store the names of four famous people. you need to know three things to assign a value to an array : 1.The name of the array that you have declared. 2.The value you want to store in to the array

3.The position in the array where you want to store the value. You can access group of variables inside an array by specifying the position inside the array. In the example below an array named myFixedArray has four positions: 0, 1, 2 and 3. Then assign some values to our array. ASP Code: <% Dim myFixedArray(3) 'Fixed size array myFixedArray(0) = "Albert Einstein" myFixedArray(1) = "Mother Teresa" myFixedArray(2) = "Bill Gates" myFixedArray(3) = "Martin Luther King Jr." %> ASP Arrays are Zero Based! If you're a good programmer you might look at that above example and think , you only allocated three elements for that array, but you assigned four values! Well, this can be done because in ASP arrays are zero based. This means when you declare fixed array of size A then you can assign values for each value from 0 through A. Below is the ASP code which is perfectly functional that will go through our array and print out the contents of each element in that array . If you are confused by this new for loop code it will be taught later.Don't worry ASP Code: <% Dim myFixedArray(3) 'Fixed size array myFixedArray(0) = "Albert Einstein" myFixedArray(1) = "Mother Teresa" myFixedArray(2) = "Bill Gates" myFixedArray(3) = "Martin Luther King Jr." For Each item In myFixedArray Response.Write(item & "<br />") Next %> O/P: Albert Einstein Mother Teresa Bill Gates Martin Luther King Jr ASP Dynamic Sized Arrays When you declare the arrayx whose size can be changed at any time simply do not put a number within the parenthesis Use the ReDim keyword when you know what size you want the array to be Use ReDim as many times as you wish. Use the Preserve keyword if you want to keep your data that already exists in the array .

Below is an example which uses ReDim Keywords ASP Code: <% Dim myDynArray() 'Dynamic size array ReDim myDynArray(1) myDynArray(0) = "Albert Einstein" myDynArray(1) = "Mother Teresa" ReDim Preserve myDynArray(3) myDynArray(2) = "Bill Gates" myDynArray(3) = "Martin Luther King Jr." For Each item In myDynArray Response.Write(item & "<br />") Next %> O/P: Albert Einstein Mother Teresa Bill Gates Martin Luther King Jr

Operators in ASP

ASP is programmed in VBScript by default, thus ASP's operators is same as VBScript operators by default

Operators in ASP are categorised into four types : 1.Math Operators. 2.Comparisons Operators. 3.Logic operators. 4.String Operators.

Arithmetic Operators

In ASP, the mathematical operators are similar to many other programming languages. However, shortcut operators are not there in ASP like ++, --, +=, etc. English Addition Subtraction Example myNum = 3 + 4 myNum = 4 - 1 Result myNum = 7 myNum = 3

Operator + -

* / ^ Mod \

Multiplication Division Exponential Modulus Negation Integer Division

myNum = 3 * 2 myNum = 9 / 3 myNum = 2 ^ 4 myNum = 23 Mod 10 myNum = -10 myNum = 9 \ 3

myNum = 6 myNum = 3 myNum = 16 myNum = 3 myNum = -10 myNum = 3

Comparison Operators

When you want to compare two values to make a decision,comparison operators are used. Comparison operators are most commonly used like "If...Then" and " Do this while something is true..." statements, otherwise known as conditional statements. The items that are most often compared are numbers. The result of a comparison operator is TRUE or FALSE. English Equal To Less Than Greater Than Less Than Or Equal To Greater Than Or Equal To Not Equal To Example 4=3 4<3 4>3 4 <= 3 4 >= 3 4 <>3 Result False False True False True True

Operator = < > <= >= <>

Logical Operators

The above comparison operators result in a truth value of TRUE or FALSE. For complex statements that must make decisions based on one or more of these truth values, a logical operator is used

10

Operator And Or Not String Operators


English Both Must be TRUE One Must be TRUE Flips Truth Value

Example True and False True or False Not True

Result False True False

The only string operator uses the string concatenation operator "&" that takes two strings and slams them together to form a new string. An example would be string1 = "Rox" and string2 = " is a Hero". The following code would combine these two strings into one: string3 = string1 & string2 English Example Result

Operator &

String Concatenation string4 = "Bob" & " runs" string4 = "Bob runs

If Statements in ASP

To make a decision in your ASP program to execute certain code if some condition is True an If Statement is used

Because VBScript is the default language to program in ASP, when you program an ASP If Statement it is actually the same as programming a VBScript If Statement.

If Statement Syntax

There is a slight difference between ASP's If Statement and the If Statement implementation in most other languages. There are no brackets, or curly braces, nor are there any parenthesis. Rather the beginning of the code to be executed in the If Statement when its true is marked with Then and the end of the If Statement is plainly marked with End If. Below is an example of If Statement that will always be True

ASP Code: <% Dim myNum myNum = 6 If myNum = 6 Then Response.Write("Variable myNum = 6") End If

11

%> O/P: Variable myNum = 6 Note: In our If Statement,you might notice that the "=" operator is used to both set the value of myNum to 6 at first, then it is used to compare myNum to 6 . In ASP,this dual use of the equals operator is confusing to many, but it might help you to remember that you cannot set the value of variables within If Statements, which means that the "=" can only compare! ASP - If Else Conditional Statement

Sometimes when the If Statement is True you might want to execute some code and some different code when it is False. Just like other programming languages, in ASP with the use of the Else keyword you can do this Below is an example in which Else portion of the If Statement is always executed as the given condition will always be false

ASP Code: <% Dim myNum myNum = 23 If myNum = 6 Then Response.Write("Variable myNum = 6") Else Response.Write("**Variable myNum = " & myNum) End If %> O/P: **Variable myNum = 23

ASP - ElseIf Conditional Statement

Whenever at a time you will want to check for multiple conditions but with a normal If Statement you can only check one condition, You can do this with ElseIf in ASP, which is the name given to an If Statement that depends on another If Statement. Think about it in plain english: If some condition is true Then do this ElseIf

12

second condition is true Then do this, etc.

In other programming languages,you may have used the ElseIf condition statement , but if not just know that you cannot have an ElseIf statement without first having an if statement. Below is an example in which second if statement (elseif) is always true.

ASP Code: <% Dim myFastfood myFastfood = "JBox" If myFastfood = "McD's" Then Response.Write("Happy Meal Por Favor!") ElseIf myFastfood = "JBox" Then Response.Write("Two tacos please!") Else Response.Write("Foot-long turkey sub.") End If %> O/P: Two tacos please!

Select Statements in ASP

In the previous lesson you learned how to setup a block of If Statements using the ElseIf keyword,but for checking multiple conditions this is not the most efficient method .

To check for multiple Is Equal To "=" conditions of a single variable,ASP uses the Select Case statement. If you are an experienced programmer you realize the Select statement resembles a Switch statement that other programming languages use for an efficient way to check a large number of conditions at one time

ASP Select Case Example

The list of case statements is checked against the variable that appears immediately after Select Case Within the Select Case block of code,these case statements are contained

13

Below is an ASP Select Case example which checks for integer values. Later we will show how to check for strings

ASP Code: <% Dim CaseNum myNum = 5 Select Case CaseNum Case 2 Response.Write("CaseNum is Two") Case 3 Response.Write("CaseNum is Three") Case 5 Response.Write("CaseNum is Five") Case Else Response.Write("CaseNum is " & myNum) End Select %> O/P: CaseNum is Five ASP Select Case - Case Else

In the last example you might have noticed something strange, there was a case that was referred to as "Case Else". This case is actually a catch all option for every case that does not fit into the defined cases. In english it might be thought of as: I'll use the "Case Else"! if all these cases don't match It is a good programming practice to always include the catch all Else case. Below we have an example that always executes the Else case

ASP Code: <% Dim CaseNum CaseNum = 454 Select Case CaseNum Case 2 Response.Write("CaseNum is Two") Case 3 Response.Write("CaseNum is Three") Case 5 Response.Write("CaseNum is Five") Case Else Response.Write("CaseNum is " & myNum)

14

End Select %> O/P: CaseNum is 454 Select Case with String Variables

So far we have only used integers in our Select Case statements, but you can also use a string as the variable to be used in the statement. Below we Select against a string

ASP Code: <% Dim CasePet myPet = "cat" Select Case CasePet Case "dog" Response.Write("I own a dog") Case "cat" Response.Write("I do not own a cat") Case Else Response.Write("I once had a cute goldfish") End Select %> O/P: I do not own a cat

Procedures in ASP

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

ASP Code:Procedures <html> <head> <% sub vbproc(num1,num2) response.write(num1*num2) end sub %>

15

</head> <body> <p> You can call a procedure like this: </p> <p> Result: <%call vbproc(4,5)%> </p> <p> Or, like this: </p> <p> Result: <%vbproc 4,5%> </p> </body> </html> O/P: You can call a procedure like this: Result: 20 Or, like this: Result: 20

ASP Procedures using JavaScript

To write procedures or functions in another scripting language than default,insert the <%@ language="language" %> line above the <html> tag

ASP Procedure Using JavaScript: <%@ language="javascript" %> <html> <head> <% function jsproc(num1,num2) { Response.Write(num1*num2) } %> </head> <body>

16

<p> Result: <%jsproc(4,5)%> </p> </body> </html> O/P: Result: 20 Differences Between VBScript and JavaScript

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

ASP Procedure Using Both VbScript And JavaScript <html> <head> <% sub vbproc(num1,num2) Response.Write(num1*num2) end sub %> <script language="javascript" runat="server"> function jsproc(num1,num2) { Response.Write(num1*num2) } </script> </head> <body> <p>Result: <%call vbproc(5,4)%></p> <p>Result: <%call jsproc(5,4)%></p> </body> </html> O/P: Result: 20 Result: 20

17

Forms in ASP

Using ASP you can process information gathered by an HTML form and use ASP code to make decisions based off this information to create dynamic web pages

To retrieve information from forms, like user input the Request.QueryString and Request.Form commands may be used An ecommerce site could take the user's information and store it into a database named user. This information could then be used to prepopulate the shipping information when the user is ordering another product By taking the title and body a forum might save the user's post to a forum and saving it to a file so that it can then be called later when someone wants to view it

Create an HTML Form


You need to create an HTML form that will send information to your ASP page,before processing the information. For sending data to an ASP form there are two methods named GET and POST. In your HTML Form element's Method attribute,these two types of sending information are defined . Also, the location of the ASP web page must be specified that will process the information Below is a simple form that will send the data using the GET method. Copy and paste this code and save it as as "vyomForm.html".

vyomForm.html Code: <form method="GET" action="vyomFormProcess.asp"> Name <input type="text" name="Name"/> Age <input type="text" name="Age"/> <input type="submit" value="Submit Query" /> </form> O/P: Name:

Age:

Submit Query

Form Example in ASP Using Method="get" <html>

18

<body> <form action="demo_reqquery.asp" method="get"> Your name: <input type="text" name="fname" size="20" /> <input type="submit" value="Submit" /> </form> <% dim fname fname=Request.QueryString("fname") If fname<>"" Then Response.Write("Hello " & fname & "!<br />") Response.Write("How are you today?") End If %> </body> </html> O/P: Your Name: Results: Hello Vyom! How are you today?

Submit

Request.QueryString

To collect values in a form with method="get",the Request.QueryString command is used . Information sent from a form with the GET method has limits on the amount of information to send and is visible to everyone (it will be displayed in the browser's address bar) . In the form example above,if a user typed "Martin" and "Luther" , the URL sent to the server would look like this:

http://www.academictutorial.com/FormProcess.asp?fname=Martin&lname=Luther ASP Code Using Request.QueryString: <body> Welcome <% response.write(request.querystring("fname")) response.write(" " & request.querystring("lname")) %> </body> In the body of the document,the browser will display the following :

19

Welcome Martin Luther Request.Form


To collect values in a form with method="post",the Request.Form command is used. Information sent from a form with the POST method has no limits on the amount of information to send and is invisible to others . In the form example above,if a user typed "Martin" and "Luther" , the URL sent to the server would look like this:

http://www.academictutorials.com/FormProcess.asp ASP Code Using Request.Form: <body> Welcome <% response.write(request.form("fname")) response.write(" " & request.form("lname")) %> </body> In the body of the document, the browser will display the following : Welcome Martin Luther

Cookies in ASP

To identify a user,a cookie is often used.

A cookie is a small text file that is stored on clientmachine that is embeded by the server. Each time the same computer requests a page with a browser, it will send the cookie too. You can both create and retrieve cookie values in ASP. To store information specific to a visitor of your website,ASP Cookies are used. For an extended amount of time this cookie is stored to the user's computer. You can set the expiration date of the cookie for some day in the future it will remain their until that day unless manually deleted by the user

How to Create a Cookie

20

To create cookies,the "Response.Cookies" command is used . BEFORE the <html> tag,the Response.Cookies command must appear We create an welcome cookie in the example below In the example below, we will create a cookie named "CountVisitors" and assign the value numvisits to it

ASP Code: <% dim numvisits response.cookies("CountVisitors").Expires=date+365 numvisits=request.cookies("CountVisitors") if numvisits="" then response.cookies("CountVisitors")=1 response.write("Welcome! This is the first time you are visiting this Web page.") else response.cookies("CountVisitors")=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: You have visited this page first time. How to Retrieve a Cookie Value?

To retrieve a cookie value,the "Request.Cookies" command is used. In the example below, we retrieve the value of the cookie named "goodname" and display it on a page

ASP Code: <% gname=Request.Cookies("goodname") response.write("Goodname=" & gname) %> O/P: Goodname=Alex A Cookie with Keys

21

We say that the cookie has Keys if a cookie contains a collection of multiple values. In the example below, we will create a cookie collection named "visitor". The "visitor" cookie has Keys that contains information about a user:

ASP Code: <% Response.Cookies("visitor")("firstname")="John" Response.Cookies("visitor")("lastname")="Smith" Response.Cookies("visitor")("country")="Norway" Response.Cookies("visitor")("age")="25" %> Read all Cookies ASP Code: <% Response.Cookies("firstname")="Alex" Response.Cookies("visitor")("firstname")="John" Response.Cookies("visitor")("lastname")="Smith" Response.Cookies("visitor")("country")="Norway" Response.Cookies("visitor")("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):li

<html> <body><% dim x,yfor 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> O/P: firstname=Alex visitor:firstname=John

22

visitor:lastname=Smith visitor:country=Norway visitor:age=25 What if a Browser Does NOT Support Cookies?

You will have to use other methods to pass information from one page to another in your application if your application deals with browsers that do not support cookies, There are two methods of doing this: 1.Add parameters to a URL 2. Use a form

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. When the user clicks on the Submit button,the form passes the user input to "welcome.asp": <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> And retrieve the values in the "welcome.asp" file like this: <% fname=Request.form("fname") lname=Request.form("lname") response.write("<p>Hello " & fname & " " & lname & "!</p>") response.write("<p>Welcome to my Web site!</p>") %>

Session in ASP

23

To store information about, or change settings for a user session, the Session object is used .

Session object is a Variables that holds information about one single user, and are available to all pages in one application In ASP,the Session Object is a great tool for the modern web site. It allows you to keep information specific to each of your site's visitors. You don't have to worry about passing information page to page because information like username, shopping cart, and location can be stored for the life of the session

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:

24

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

25

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 %> O/P: username age You can use the Count property if you do not know the number of items in the Contents collection,: <% 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 %> O/P:

26

Session variables: 2 Donald Duck 50 Loop Through the StaticObjects Collection To see the values of all objects stored in the Session object you can loop through the StaticObjects collection,: <% dim i For Each i in Session.StaticObjects Response.Write(i & "<br />") Next %>

Application in ASP

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")=""

27

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 Loop Through the Contents Collection All application variables wil be stored in Contents collection .To see what's stored in it ,you can loop through the Contents collection, : <% dim i For Each i in Application.Contents Response.Write(i & "<br />") Next %> You can use the Count property if you do not know the number of items in the Contents collection, : <% dim i dim j j=Application.Contents.Count For i=1 to j Response.Write(Application.Contents(i) & "<br />") Next %> Loop Through the StaticObjects Collection To see the values of all objects stored in the Application object,you can loop through the StaticObjects collection : <% dim i For Each i in Application.StaticObjects Response.Write(i & "<br />") Next %>

28

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

ASP Response Object


To send output to the user from the server, the ASP Response object is used. 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: Collection Cookies Properties Property Buffer CacheControl Charset ContentType Expires ExpiresAbsolute Description Specifies whether to buffer the page output or not Sets whether a proxy server can cache the output generated by ASP or not Appends the name of a character-set to the content-type header in the Response object Sets the HTTP content type for the Response object Sets how long (in minutes) a page will be cached on a browser before it expires Sets a date and time when a page cached on a browser will expire Appends a value to the PICS label response header Specifies the value of the status line returned by the server Description Sets a cookie value. If the cookie does not exist, it will be created, and take the value that is specified

IsClientConnected Indicates if the client has disconnected from the server Pics Status

29

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

AppendToLog Adds a string to the end of the server log entry

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!

30

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

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

ASP Request Object


To get information from the user, the ASP Request object is used.

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 Cookies Form QueryString Description Contains all the cookie values sent in a HTTP request Contains all the form (input) values from a form that uses the post method Contains all the variable values in a HTTP query string

ClientCertificate Contains all the field values stored in the client certificate

ServerVariables Contains all the server variable values Properties Property TotalBytes Description Returns the total number of bytes the client sent in the body of the request

32

Methods Method BinaryRead Description Retrieves the data sent to the server from the client as part of a 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: Your Name: Results: Hello Ravi! How are you today?

Submit

33

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>

34

</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: User Name: Password
Submit Reset

Your Username was: rabi Your Password was: rabi

ASP ADO Object


To access databases from your web pages, ADO can be used .

Accessing a Database from an ASP Page To access a database from inside an ASP page,the common way is to: 1. 2. 3. 4. 5. 6. Create an ADO connection to a database Open the database connection Create an ADO recordset Open the recordset Extract the data you need from the recordset Close the recordset

7. Close the connection What is ADO?


ADO stands for ActiveX Data Objects ADO is a Microsoft technology ADO is automatically installed with Microsoft IIS ADO is a Microsoft Active-X component ADO is a programming interface to access data in a database

35

ASP Ad Rotator
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.

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

36

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.academictutorials.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 Border Description Specifies the size <% Example

37

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

Clickable

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

Returns HTML that <% GetAdvertisemen displays the Response.Write(adrot.GetAdvertisement("ads.txt")) advertisement %> in the page

38

Vous aimerez peut-être aussi