Sie sind auf Seite 1von 51

Active Server Pages

Minder Chen, Ph.D.


mchen@gmu.edu

Minder Chen, 1998-2002

ASP - 1

Creating ASP Page


ASP uses the delimiters <% and %> to enclose script commands. By default, the primary scripting language is VBScript.

test.asp
<HTML> <BODY> This page was last refreshed on <% =Now() %>. </BODY> </HTML> The VBScript function Now returns the current date and time. <HTML> <BODY> Rendered This page was last refreshed on 9/11/98 4:30:00 PM. via a </BODY> browser </HTML>
Interpreted ASP code: An HTML document.
Minder Chen, 1998-2002

This page was last refreshed on 9/11/98 4:30:00 PM.


ASP - 2

The Active Server Pages Model


Web Server

(IIS)
Browser

.asp files Active Server Page

ASP
Interpreter:
Process ASP Scripting Statements

An ASP script begins to run when a browser requests a .asp file from your Web server. Your Web server then calls ASP, which reads through the requested file from top to bottom, executes any ASP statements, and sends an HTML page to the browser.
Minder Chen, 1998-2002 ASP - 3

ASP Scripting
The first line in an .asp file specifies the scripting language for the page. For example, the following first line in .asp file specifies that the script is VBScript:
<%@ LANGUAGE=VBScript %>

Without a language tag, script in the file is processed as the default language (VBScript by default.) Active Server Pages can provide a scripting environment for a number of other scripting languages, including Jscript and others.

Minder Chen, 1998-2002

ASP - 4

Hello.asp: Display Information


<HTML> <HEAD>
<TITLE>Hello World Example</TITLE> Returned HTML Document

<HTML> <HEAD>
<TITLE>Hello World Example</TITLE>

</HEAD> <BODY> <%


%>

The start of the script section

</HEAD> <BODY> Hello World!

Response.write

</BODY> "Hello World!" </HTML>


method
Build-in Object

Argument

</BODY> </HTML>

The end of script section


ASP - 5

Minder Chen, 1998-2002

Hello2.asp
<HTML><HEAD> <TITLE>HELLO WORLD</TITLE> </HEAD><BODY> <% FOR i = 3 to 7 %> <FONT SIZE = <% =i %>> Hello World!<BR> <% NEXT %> </BODY></HTML>
Return HTML Source Code <HTML><HEAD> <TITLE>HELLO WORLD</TITLE> </HEAD><BODY> <FONT SIZE = 3> Hello World!<BR>

<FONT SIZE = 4> Hello World!<BR>


<FONT SIZE = 5> Hello World!<BR>

http://localhost/asp/hello.asp

<FONT SIZE = 6> Hello World!<BR>


<FONT SIZE = 7> Hello World!<BR>

</BODY></HTML>
Minder Chen, 1998-2002 ASP - 6

Hello3.asp
<% ' Define two variables with string values. x = "Hello" y = "World" %> <P>My response is to say "<%= y %>&nbsp; <%= x %>." </P>
<% Color = "Green" %> <%Color="Green"%> <% Color = "Green"

Same result

%>
Minder Chen, 1998-2002

ASP - 7

Hello4.htm: Sample JavaScript Code


<HTML><HEAD><TITLE>HELLO WORLD</TITLE></HEAD> <BODY> <% Response.write("Hello world! -- From ASP") %> <SCRIPT LANGUAGE="JavaScript1.2"> document.write("<P>Hello world! -- From Client-Side Scripting!") </SCRIPT> <P>Hello World! -- From HTML </BODY> </HTML>

Minder Chen, 1998-2002

ASP - 8

Data Types
Variables: Simple variables and Array variables VBScript subsumes all categories of data under one name called a Variant. At a basic level, Variants contain either string or numeric data. String data is used for text, while numeric data contains only numbers. Variant data can be further classified into subtypes. For example, you can have numeric data that represents currency, or a date or time, and the Variant will interpret the data accordingly. You can use the data type conversion function for data
type conversion. For example, CInt function to force conversion of an expression to the Variant of subtype

Integer.
Minder Chen, 1998-2002 ASP - 9

Data Types
Empty
Variant is uninitialized. Value is 0 for numeric variables or a zerolength string ("") for string variables.

Null
Variant intentionally contains no valid data.

Boolean
Contains either True or False.

Byte
Contains integer in the range 0 to 255.

Integer
Contains integer in the range -32,768 to 32,767.

Currency
-922,337,203,685,477.5808 to 922,337,203,685,477.5807.

Long
Contains integer in the range -2,147,483,648 to 2,147,483,647.

Minder Chen, 1998-2002

ASP - 10

Data Types
Single
Contains a single-precision, floating-point number in the range 3.402823E38 to -1.401298E-45 for negative values and 1.401298E-45 to 3.402823E38 for positive values.

Double
Contains a double-precision, floating-point number in the range -1.79769313486232E308 to -4.94065645841247E-324 for negative values and 4.94065645841247E-324 to 1.79769313486232E308 for positive values.

Date (Time)
Contains a number that represents a date or time between January 1, 100 to December 31, 9999.

String
Contains a variable-length string that can be up to approximately two billion characters in length.

Object
Contains an object.

Error
Contains an error number.
Minder Chen, 1998-2002 ASP - 11

Declaring Variables
VBScript implicitly creates a variable the first time that it encounters an unrecognized string of characters that could be a variable name. The Option Explicit statement informs VBScript to generate an error if it encounters an undeclared variable. The Option Explicit statement should be the first line of code in a script that uses variables. Dim varname Dim a A variable name:
Must begin with an alphabetic character.
Cannot contain an embedded period. Must not exceed 255 characters. Must be unique.

Is not case-sensitive.

Constants:
Const CorpName = "Volcano Coffee Company" Const HousePayment = 1500
Minder Chen, 1998-2002 ASP - 12

Exercise: Variable.asp
<% Option Explicit %> <html><head><title>Variables</title><head> <body> <% Dim x, y, x1, a, b, c x=1 y=2 response.write x+y x1=6 response.write x1 & "<br>" a =5 b=7 c= a + b response.write a + b & "<br>" response.write a & b & "<br>" %> </body></html>
Minder Chen, 1998-2002

Have to be the first line

Declare a variable with a data type is not allowed: Dim x as Integer

ASP - 13

Response Object: Write Method


<HTML><HEAD><TITLE>Hello World</TITLE> </HEAD> <BODY> <% response.write "Hello World" %> </BODY> <HTML><HEAD><TITLE>Message</TITLE></HEAD><BODY > <% Dim message message = "Hello World" Hello World Response.Write message %> </BODY></HTML>
Minder Chen, 1998-2002 ASP - 14

Math Operations
<HTML><HEAD><TITLE>Math Operations</TITLE></HEAD><BODY>

<% A = 7 B = 3 Response.Write Response.Write Response.Write Response.Write Response.Write Response.Write Response.Write %> </BODY></HTML>

A & " + "<BR>" A & " "<BR>" A & " * "<BR>" A & " /

" & B & " = " & A + B


" & B & " = " & A - B

" & B & " = " & A * B


" & B & " = " & A / B

7 + 3 = 10 7-3=4 7 * 3 = 21 7 / 3 = 2.33333333333333
ASP - 15

Minder Chen, 1998-2002

Decision Making and Branching


To vary the flow of a script, you use conditional statements (also known as control structures) to makes decisions during program execution. The conditional statements include test expressions that are evaluated as the program runs and, based upon their results, control the program flow. The two control structures that you will learn include
IfThenElse Select Case.

Minder Chen, 1998-2002

ASP - 16

Control Flow

True Block

False Block
ASP - 17

Minder Chen, 1998-2002

Making Decision Using Select Case


A Select Case structure works with a single test expression that is evaluated once at the top of the structure. The result of the expression is then compared with the values for each Case in the structure. If there is a match, the block of statements associated with that Case is executed. Use the Case Else statement to handle any condition that did not match a specified case.

Minder Chen, 1998-2002

ASP - 18

Example
Dim Color, MyVar Sub ChangeBackground (Color) MyVar = lcase (Color) Select Case MyVar Case "red" bgColor = "red" Case "green" bgColor = "green" Case "blue" bgColor = "blue" Case Else bgColor = "white" End Select End Sub

Minder Chen, 1998-2002

ASP - 19

Loops
<HTML><HEAD><TITLE>Loops</TITLE></HEAD><BODY> <% Dim iCount For iCount = 1 to 5 1 Response.Write iCount 2 Response.Write "<BR>" 3 Next 4 For iCount = 10 to 0 step -2 5 Response.Write iCount 10 Response.Write "<BR>" 8 Next 6 %> 4 </BODY></HTML> 2

Minder Chen, 1998-2002

ASP - 20

Loops Statements
VBScript includes the following looping constructions:
Do...Loop: repeats statements while or until a test condition is met. For...Next: repeats statements a specified number of times. For Each element In group Next: repeats statements for each occurrence of a specific item in a specified group.

Minder Chen, 1998-2002

ASP - 21

Loop: Do While Loop


<% Check condition at the Dim Counter beginning of the loop Counter = 1 Do While Counter < 3 Response.Write "Counter = " & Counter & "<br>" Counter = Counter + 1 Loop

%>

Counter = 1 Counter = 2
Minder Chen, 1998-2002 ASP - 22

Do Loop While
Dim Counter Counter = 1 Do Response.Write "Counter = " & Counter & "<br>" Counter = Counter + 1 Loop While Counter < 3
Check condition at the end of the loop

Minder Chen, 1998-2002

ASP - 23

Do Until
To check the test condition at the beginning of the loop, change the following statement: Do While Counter<3 . Loop to the following: Do Until Counter>=3 Loop To check the condition at the end of the loop, change the following statement: Do Loop While Counter<3

to the following:
Do Loop Until Counter>=3
ASP - 24

Minder Chen, 1998-2002

Form Input Data Processing


form4.htm <HTML><HEAD><TITLE>Form Input</TITLE></HEAD><BODY> <FORM METHOD=POST ACTION="answer04.asp"> Name: <INPUT TYPE=TEXT NAME="UserName"> <INPUT TYPE=SUBMIT> </FORM></BODY></HTML>

answer04.asp
<HTML><HEAD><TITLE>Form Input Processing</TITLE></HEAD><BODY>

<% Response.Write Request.Form("UserName") %> </BODY></HTML>


ASP - 25

Minder Chen, 1998-2002

Exercise: Form Input Data Processing

<input type=text name=UserName>

Minder Chen, 1998-2002

ASP - 26

Form.htm
<HTML><HEAD><TITLE>Order</TITLE></HEAD><BODY> <H2>Sample Order Form</H2> Please fill out this form, then click Submit:<P> <FORM METHOD="POST" ACTION="response.asp"> First Name: <INPUT NAME="fname" SIZE="48"><br> Last Name: <INPUT NAME="lname" SIZE="48"><br> Title: <INPUT NAME="title" TYPE=RADIO VALUE="mr">Mr. <INPUT NAME="title" TYPE=RADIO VALUE="ms">Ms. <P><INPUT TYPE=SUBMIT><INPUT TYPE=RESET> </FORM></BODY></HTML>

http://127.0.0.1/vbscriptlab/form.htm

Minder Chen, 1998-2002

ASP - 27

Response.asp
<%@ LANGUAGE = VBScript %> <HTML> <HEAD><TITLE>Response.asp File</TITLE></HEAD> <BODY BGCOLOR="#FFFFFF"><FONT FACE="ARIAL,HELVETICA"> <H2><CENTER>Order Received</CENTER></H2> <P ALIGN=CENTER> <%= Request.Form("fname") & " " & Request.Form("lname")%> </FONT> </BODY> </HTML>

Minder Chen, 1998-2002

ASP - 28

Response2.asp
<%@ LANGUAGE = VBScript %> <HTML> <HEAD><TITLE>Response.asp File</TITLE></HEAD> <BODY BGCOLOR="#FFFFFF"><FONT FACE="ARIAL,HELVETICA"> <H2><CENTER>Order Received</CENTER></H2> <P ALIGN=CENTER> <% Title = Request.Form("title") %> <% LastName = Request.Form("lname") %> <%If Title = "mr" Then %> Mr. <%= LastName %> Change the action attribute <% ElseIf Title = "ms" Then %> of form.htm to response2.asp Ms. <%= LastName %> and save it as form2.htm <% Else %> <%= Request.Form("fname") & " " & LastName %> <% End If %> </FONT> </BODY> </HTML>
Minder Chen, 1998-2002 ASP - 29

Exercise: Calculator
Operator can be: +, -, *, / Check divide-by-zero error
Cal.htm

A*B=600
Minder Chen, 1998-2002 ASP - 30

Cal.htm
<HTML><HEAD><TITLE>Calculator</TITLE></HEAD><BODY> <form method="post" action="cal.asp"> First Number: <Input type="text" name="x1"><br> Operator is: <select name="op"> <option>+ <option><option>* <option>/ </select><br> Second Number: <Input type="text" name="x2"><br> <input type="submit" value="Calculate" > </form> </BODY></HTML>

Minder Chen, 1998-2002

ASP - 31

Cal.asp
<HTML><HEAD><TITLE>Calculator</TITLE></HEAD><BODY> <% If Request.Form("x1")="" Then Response.Write "The first number is missing <br>" If Request.Form("x2")="" Then Response.Write "The 2nd number is missing <br>" End If Response.end Else If Request.Form("x2")="" Then Response.Write "The 2nd number is missing <br>" Response.End End If End If A = CSng(Request.Form("x1")) ' Convert to single precision B = CSng(Request.Form("x2"))
Minder Chen, 1998-2002 ASP - 32

Continued...
Select Case Request.Form("op") Case "+" C=A+B Response.write "A+B=" & C Case "-" C=A-B Response.write "A-B=" & C Case "*" C=A*B Response.write "A*B=" & C Case "/" If B<>0 Then Temp=A/B C=Round(Temp,2) ' Round it to 2 decimal places Response.Write "A/B=" & C Else Response.write "The second number cannot be zero." & "<br>" Response.write "Use BACK navigation button to change it!" & "<br>" End If Case Else Response.Write "You need to choose an operator" End Select %> </BODY></HTML>
Minder Chen, 1998-2002 ASP - 33

Exercise: sub1.asp
<HTML><HEAD><TITLE>Subroutine</TITLE> <% Sub MySub(iNum) Response.Write iNum * iNum sub2.asp End Sub <HTML><HEAD><TITLE>Subroutine</TITLE> %> <% Sub MySub(iNum, iSquare) </HEAD><BODY> iSquare = iNum * iNum End Sub <% %> Dim a </HEAD><BODY> <% a = 20 Dim a, b a = 20 MySub a MySub a, b Response.write "The square value of " & a & " is " & b %> %> </BODY></HTML> </BODY></HTML>
Minder Chen, 1998-2002 ASP - 34

Scope of a Variable
If a variable is declared outside of a procedure, it is visible throughout the program. If a variable is declared inside a procedure, it is only visible inside that procedure. The range of a variables visibility is called its scope.

Minder Chen, 1998-2002

ASP - 35

Functions
Function fName(arg1, arg2, ...) ... fName = expression

...
End Function
Create a variable with the same name as the Function. Assign the return value to that variable. Arguments, including constants, variables, and expressions, are passed to the Function procedure, which can then use the arguments. Function arguments are placed inside parentheses. If no arguments are passed, empty parentheses are required.
Minder Chen, 1998-2002 ASP - 36

Functions: temp2.asp
<% Function Celsius(fDegrees) Celsius = (fDegrees - 32) * 5 / 9 End Function

Sub ConvertTemp(tempF, tempC) tempC = Celsius(tempF)


End Sub %>

Function Celsius(fDegrees) appears before Sub ConvertTemp() because the Sub procedure, ConvertTemp, calls the Function procedure, Celsius.

<html><head><title>Temperature</title></head><body> <%
Dim tempX tempX = Request.Form("InTemp")

Temp2.htm

' Calls the Sub procedure ConvertTemp tempX, tempY Response.write tempY
Response.write " degrees C."

%>
Minder Chen, 1998-2002

<HTML><HEAD><TITLE>Tempreture</TITLE></ HEAD> <BODY> <H2>Temperature Conversion Form</H2> <FORM METHOD="POST" ACTION="temp2.asp"> <P> What is the temperature in Degree F: <br> <INPUT NAME="inTemp" SIZE="48"><br> <P><INPUT TYPE=SUBMIT><INPUT TYPE=RESET> </FORM></BODY></HTML>
ASP - 37

Object, Property and Method


You can create an instance of an object by using the Server.CreateObject statement. An object can contain callable program code called methods and data called properties.

Dot notation objectName.propertyName objectname.methodName objectname.methodName(arg1, arg2, )

Minder Chen, 1998-2002

ASP - 38

QueryString Collection
The QueryString collection retrieves form values passed to your Web server using HTTP GET method or retrieves variable-value pairs set as text followed a question mark in the request URL. Example:
<FORM METHOD="GET" ACTION="profile.asp"> <INPUT TYPE="text" NAME="firstname"> <INPUT TYPE="text" NAME="lastname"> <INPUT TYPE="text" NAME="age"> <INPUT TYPE="hidden" NAME="userstatus" VALUE= "new"> <INPUT TYPE="submit" VALUE="Enter"> </FORM>

Minder Chen, 1998-2002

ASP - 39

Process Input Data from the QueryString


If the user typed Jeff, Smith, and 30, then the following URL request would be sent to the server:
http://scripts/profile.asp?firstname=Jeff&lastname=Smith&age=30 &userstatus=new

profile.asp: Hello, <%= Request.QueryString("firstname") %> <%= Request.QueryString("lastname") %>. You are <%= Request.QueryString("age") %> years old. <% If Request.QueryString("userstatus") = "new user" then Response.Write "This is your first visit to this Web site!" End if %>

Hello, Jeff Smith. You are 30 years old. This is your first visit to this Web site!
ASP - 40

Minder Chen, 1998-2002

Multiple Values of a Variable


The QueryString collection has an optional parameter Counter that you can to count the number of times that a specific variable appears. A request of a form containing a list box with multiple items: http://scripts/list.asp?food=apples&food=olives&food=bread Command to count multiple values:

Request.QueryString("food").Count
To display the multiple values types, List.asp could contain the following script:
<%Total = Request.QueryString("food").Count%> <%For i = 1 to Total%> <%= Request.QueryString("food")(i) %> <BR> <%Next%>

The preceding script would display: apples olives bread


Minder Chen, 1998-2002 ASP - 41

Use ADO
The Database Access component uses Active Data Objects (ADO) to provide easy access to information stored in a database that complies with the Open Database Connectivity (ODBC) standard. You will learn how to extract data using the SQL SELECT statement and create an HTML table to display the results.

Minder Chen, 1998-2002

ASP - 42

Identify the Database


Before using a database with the Database Access component, you must identify the database in the ODBC application in Control Panel. In this example, you will use a Microsoft Access database that is provided with the ASP sample Web site. At the computer running your Web server, open Control Panel. Double-click the ODBC icon, and then click System DSN. There are two types of data sources: User, which is available only to you, and System, which is available to anyone using the computer. Data sources for use with the Web server need to be of the System type. Click Add, choose the Microsoft Access Driver, and then click Finish. In the Data Source Name box, type ASP Tutorial DB, and then click Select. Select the c:\Webshare\asp\AdvWorks.mdb file and click OK. Click OK to close the dialog boxes.

Minder Chen, 1998-2002

ASP - 43

Set Up ODBC Data Source

Minder Chen, 1998-2002

ASP - 44

Deptlist.asp
<HTML><HEAD><TITLE>Department Listing</TITLE></HEAD><BODY> <H1>Department List</H1> <% Set dbConnection =Server.CreateObject("ADODB.Connection") dbConnection.Open "expense" SQLQuery ="SELECT * FROM Departments" Set RSDeptList = dbConnection.Execute(SQLQuery) %> <UL> <% Do While Not RSDeptList.EOF %> <LI> <%= RSDeptList("ID")%> &nbsp; <%= RSDeptList("name")%> :&nbsp; <%= RSDeptList("description")%> <% RSDeptList.MoveNext Loop dbConnection.close set dbConnection = Nothing %> </UL></BODY></HTML>
Minder Chen, 1998-2002 ASP - 46

Using Table

Minder Chen, 1998-2002

ASP - 47

OLE DB Connection String Microsoft Access


Provider=Microsoft.Jet.OLEDB.4.0;Data Source=physical path to database file

Microsoft SQL Server


Provider=SQLOLEDB.1;Data Source=path to server

Oracle
Provider=MSDAORA.1;Data Source=path to server

Microsoft Indexing Service


Provider=MSIDXS.1;Data Source=path to index file
Minder Chen, 1998-2002 ASP - 48

Insert
<% 'Define the OLE DB connection string.
strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Data\Employees.mdb"

'Instantiate the Connection object and open a database connection. Set cnn = Server.CreateObject("ADODB.Connection") cnn.Open strConnectionString 'Define SQL SELECT statement. strSQL = "INSERT INTO Customers (FirstName, LastName) VALUES ('Jose','Lugo')" 'Use the Execute method to issue a SQL query to database. cnn.Execute strSQL, ,adCmdText + adExecuteNoRecords

%>

Minder Chen, 1998-2002

ASP - 49

Update and Delete


<% Set cnn = Server.CreateObject("ADODB.Connection") cnn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Data\Employees.mdb" cnn.Execute _
"UPDATE Customers SET FirstName ='Jeff' WHERE LastName = 'Smith' " _ , ,adCmdText + adExecuteNoRecords

%> <% Set cnn = Server.CreateObject("ADODB.Connection") cnn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Data\Employees.mdb" cnn.Execute _ "DELETE FROM Customers WHERE LastName = 'Smith'" _ ,,adCmdText + adExecuteNoRecords %>

Minder Chen, 1998-2002

ASP - 50

ASP and Session Management


Hypertext Transfer Protocol (HTTP) is a stateless protocol. Each browser request to a Web server is independent, and the server retains no memory of a browser's past requests. The Session object, one of the intrinsic objects supported by ASP, provides a developer with a complete Web session management solution. The Session object supports a dynamic associative array that a script can use to store information. For each ASP page requested by a user, the Session object will preserve the information stored for the user's session. This session information is stored in memory on the server. The user is provided with a unique session ID that ASP uses to match user requests with the information specific to that user's session.

A session is terminated when you close the browser.


Minder Chen, 1998-2002 ASP - 51

Err.asp
<HTML><HEAD><TITLE>The Err Object</TITLE></HEAD><BODY> <% On Error Resume Next Response.Write "10 / 0 =" & 10/0 IF Err.Number <> 0 THen Response.Write "<BR>Err.Description =" & Err.Description Response.Write "<BR>Err.Number=" & Err.Number Response.Write "<BR>Err.Source=" & Err.Source Response.Write "<BR>Err.HelpFile=" & Err.HelpFile Response.Write "<BR>Err.HelpContext =" & Err.HelpContext Response.write "<p>Stop" Response.End Err.Description =Division by zero Else Err.Number=11 Err.Source=Microsoft VBScript runtime error Response.Write "<p>OK" Err.HelpFile= End If Err.HelpContext =0 %> </BODY></HTML>

Minder Chen, 1998-2002

ASP - 52

Das könnte Ihnen auch gefallen