Vous êtes sur la page 1sur 10

4-1 ASP 1

4.1 ASP
What is ASP?
− ASP is a server-side scripting technology for building dynamic and interactive web pages.
− An Active Server Page is a text file script with the extension .asp, containing HTML, client-
side and server-side scripting.
− Features of ASP in terms of syntax and grammar:
î It supports some interaction between the page user and the server.
î It allows web page access to databases and directory services.
î It incorporates and makes use of high-powered COM components.
− Features of ASP in terms of usage:
î The static content of the page can be generated using HTML and text.
î The dynamic elements of the web page can be created by calling any of ASP's intrinsic
objects (Request, Response, Application, Server, Session).
î There is access to the functionality of standard scripting languages such as VBScript,
Jscript, JavaScript, etc. and their respective scripting objects.
î Any standard COM object can be incorporated into the web page.

Working of ASP
1. Client requests an ASP page.
2. If server cannot locate requested page, an "HTTP 404 Page Not Found" message is
displayed.
3. If server locates the required .asp file, it is sent to the ASP Scripting Engine to be parsed.
4. The Scripting Host (located in asp.dll) may begin a new session and application by sending
the first ASP file to the client.
5. After checking the global.asa file, it executes all the server-side scripting enclosed in the
<%...%> or <SCRIPT RUNAT=SERVER> tags.
6. Finally, the engine passes back one of the three things:
(a) an error page [probably based on validated data]
(b) "object moved" status code [if a Response.Redirect call is found in the code]
(c) an HTML page [response page]
− There are four broad categories of ASP components:

ASP Object Model


− ASP's intrinsic objects are immediately accessible to the developer, and they cover all key
aspects of creating dynamic and interactive web pages.
− At the top of the hierarchy is the ScriptingContext object which is created automatically
when any block of ASP code is run, and it is responsible for making the intrinsic aspects and
object of ASP available to the scripting host.
− The Request and Response objects are known as Objects of Conversation, where the
website receives Request objects from the client browser, and responds to the same with
Response objects.
− The Application and Session objects are known as Objects of State, and they provide
virtual memory for a web application to run correctly and retain state.
− The Server object contains miscellaneous methods that the server performs.

[When asked to explain all objects in brief, give one line about the purpose of each object,
and provide a listing of the Collections, Properties, Methods and Events of each object].

PDF created with pdfFactory Pro trial version www.pdffactory.com


4-1 ASP 2

Request Object
− The Request object retrieves the values that the client browser passed to the server during
an HTTP request.
Request[.collection|property|method](variable)

− Collections
î ClientCertificate: To get the certification fields from the request issued by the Web
browser. The fields that you can request are specified in the X.509 standard
î Cookies: The values of cookies sent in the HTTP request.
î Form: The values of form elements in the HTTP request body.
î QueryString: The values of variables in the HTTP query string.
î ServerVariables: The values of predetermined environment variables.
− Properties
î TotalBytes: Read-only. Specifies the total number of bytes the client is sending in the
body of the request.
− Methods
î BinaryRead: Retrieves data sent to the server from the client as part of a POST request.
Variable parameters are strings that specify the item to be retrieved from a collection or
to be used as input for a method or property.
− All variables can be accessed directly by calling Request(variable) without the collection
name, in which case, the Web server searches the collections in the following order:
QueryString, Form, Cookies, ClientCertificate, ServerVariables.
− If a variable with the same name exists in more than one collection, the Request object
returns the first instance that the object encounters.
− Request.ServerVariables (some of them)
QUERY_STRING Variable name value pairs from the URL string
REQUEST_METHOD Method of request
CONTENT_LENGTH Length of the content
CONTENT_TYPE MIME type of the current page
SERVER_NAME Server name
SERVER_PORT Port being accessed

The Response object


− The Response object is used to send information to the user.
Response.collection|property|method

− Collections
î Cookies: Specifies cookie values. Using this collection, you can set cookie values.
− Properties
î Buffer: Indicates whether page output is buffered.
î CacheControl: Determines whether proxy servers are able to cache output generated by
ASP.
î Charset: Appends the name of the character set to the content-type header.
î ContentType: Specifies the HTTP content type for the response.
î Expires: Specifies the length of time before a page cached on a browser expires.
î ExpiresAbsolute: Specifies the date and time on which a page cached on a browser
expires.
î IsClientConnected: Indicates whether the client has disconnected from the server.
î Pics: Adds the value of a PICS label to the pics-label field of the response header.
î Status: The value of the status line returned by the server.
− Methods

PDF created with pdfFactory Pro trial version www.pdffactory.com


4-1 ASP 3

î AddHeader: Sets the HTML header name to value.


î AppendToLog: Adds a string to the end of the Web server log entry for this request.
î BinaryWrite: Writes the given information to the current HTTP output without any
character-set conversion.
î Clear: Erases any buffered HTML output.
î End: Stops processing the .asp file and returns the current result.
î Flush: Sends buffered output immediately.
î Redirect: Sends a redirect message to the browser, causing it to attempt to connect to a
different URL.
î Write: Writes a variable to the current HTTP output as a string. This can be done by using
the construct:
Response.Write("Hello") or <%= "Hello" %>

The Server object


− The Server object provides access to methods and properties on the server.
− Most of these methods and properties serve as utility functions.
Server.property|method

− Properties
î ScriptTimeout: The amount of time that a script can run before it times out.
− Methods
î CreateObject: Creates an instance of a server component. This component can be any
component that you have installed on your server (such as an ActiveX ).
î HTMLEncode: Applies HTML encoding to the specified string.
î MapPath: Maps the specified virtual path, either the absolute path on the current server
or the path relative to the current page, into a physical path.
î URLEncode: Applies URL encoding rules, including escape characters, to the string.

The Session object


− You can use the Session object to store information needed for a particular user-session.
− Variables stored in the Session object are not discarded when the user moves between
pages in the application; instead, these variables persist for the entire user-session.
− The Web server automatically creates a Session object when a Web page from the
application is requested by a user who does not already have a session.
− The server destroys the Session object when the session expires or is abandoned.
− One common use for the Session object is to store user preferences.
− For example, if a user indicates that they prefer not to view graphics, you could store that
information in the Session object.
− Note that Session state is only maintained for browsers that support cookies.
Session.collection|property|method

− Collections
î Contents: Contains the items that you have added to the session with script commands.
î StaticObjects: Contains the objects created with the <OBJECT> tag and given session
scope.
− Properties
î CodePage: The codepage that will be used for symbol mapping.
î LCID: The locale identifier.
î SessionID: Returns the session identification for this user.
î Timeout: The timeout period for the session state for this application, in minutes.

PDF created with pdfFactory Pro trial version www.pdffactory.com


4-1 ASP 4

− Methods
î Abandon: This method destroys a Session object and releases its resources.
− Events (Scripts for the following events are declared in the global.asa file.)
î Session_OnEnd: The activities to perform when a session ends.
î Session_OnStart: The activities to perform when a session begins.

The Application object


− The Application object can store information that persists for the entire lifetime of an
application (a group of pages with a common root).
− Any information that has to exist for or be shared among more than one users (such as a
page counter) can be stored using this object.
− Values stored in the Application collections are available throughout the application and
have application scope.
− But since this object isn't created anew for each user, errors that may not show up when
the code is called once may show up when it is called 10,000 times in a row.
− Also, since the Application object is shared by all the users, threading is difficult.
− An ASP-based application is defined as all the .asp files in a virtual directory and its
subdirectories.
− Because the Application object can be shared by more than one user, there are Lock and
Unlock methods to ensure that multiple users do not try to alter a property simultaneously.
Application.method

− Collections
î Contents: Contains all of the items that have been added to the Application through script
commands.
î StaticObjects: Contains all of the objects added to the session with the <OBJECT> tag.
î Lock: The Lock method prevents other clients from modifying Application object
properties.
î Unlock: The Unlock method allows other clients to modify Application object properties.
− Events (Scripts for the following events are declared in the global.asa file.)
î Application_OnEnd
î Application_OnStart

Processing Forms
The Request.Form Collection
− Consider the following example:
<FORM METHOD="post" ACTION="process.asp">
<INPUT TYPE="text" NAME="FirstName">
<INPUT TYPE="text" NAME="LastName">
<INPUT TYPE="radio" NAME="Gender" VALUE="M">
<INPUT TYPE="radio" NAME="Gender" VALUE="F">
<TEXTAREA NAME="Address">
</TEXTAREA>
<INPUT TYPE="submit" VALUE="Send">
</FORM>
− The fields in the form above are FirstName (Text), LastName (Text), Gender (Option: M or
F), and Address (Multiline Text), along with the "submit" button, required to submit the
user input to the script.
− On clicking the Submit button, the contents of each of these fields are posted to the script
that you specified in the FORM Action attribute, in this case, "process.asp "

PDF created with pdfFactory Pro trial version www.pdffactory.com


4-1 ASP 5

− The form processing script can access these input values as: Request.Form ("FirstName")
and use them for different purposes, either directly, or store them into variables and use
them.
− Please note that the METHOD specified in the FORM tag must be POST if you want to use
the Request.Form collection to process it.

The Request.QueryString Collection


− The Query String forms part of a URL, and can be used to pass multiple values as well.
− The Request.QueryString Collection helps sort out those multiple values and extract only
what is needed, i.e. the values of the variables themselves.
− So to access the data contained in the variable FirstName above:
Request.QueryString ("FirstName")

− This again, is a regular variable that is available for further processing.


− The Request.QueryString collection gives you access to yet another class of variables –
those passed via a FORM with it’s METHOD = "GET".
− However, there is a limit to the amount of data that can be passed on via the QueryString
and you are expected to use a form for more data.

When to use GET and when to use POST?


− GET may be used for small amounts of data because here, data items are appended to the
URL by your browser, and you cannot have an infinitely long URL (with the QueryString).
− It is a good idea to use POST for your forms, as there is no limit to how much data can be
sent using the POST method, and it also does not reveal the data being sent on the address
bar.

ASP Applications
− A web application is a collection of ASP pages and server components.
− All content is placed within a root directory, and the scope of the application is defined by
the directories under the root directory.
− Each application has a set of variables and attributes maintained throughout the lifetime of
the application.
− The global.asa file initializes and destroys the application and session objects that are used
to store info for the duration of the application and session respectively.
− The global.asa file is stored in the root directory and is valid throughout the scope of this
application.

ASP Components
− There are four broad categories of ASP components:
î Presentation components: Help develop the user interface.
î Business components: Encapsulate business logic, such as standard rules to validate
credit card information.
î Data components: Help simplify page querying.
î Utility components: Help perform utility functions such as file uploading, etc.

PDF created with pdfFactory Pro trial version www.pdffactory.com


4-1 ASP 6

The ADO Object Model


− Following is a representation of the ADO Object Model

− As shown above, there are three main objects: the Connection, the Command, and the
Recordset.
− Each of these (including the Field object) has a collection of Properties.
− Connection
î It contains all the details about a specific connection to a data store, such as data store
name, user name, database name, etc.
î The connection object not only provides connectivity with the database, but also allows
querying and execution of SQL statements such as CREATE, DELETE, etc.
− Command
î It allows the execution of SQL commands that are action-based and that return results.
î It is mainly used for stored procedures with parameters.
− Recordset
î It is the container for a set of records, returned from a command.
î It allows navigation through the records, as well as adding, deleting, and updating
records.
− Fields
î The Fields collection is equivalent to the set of columns of a result set, where each field is
a Field object representing a single value.
î There is one Fields collection for every row of a Recordset.
− Errors
î Errors that occur during the processing of commands are placed in the Errors collections.
− Parameters
î The Parameters collection belongs to the Command object and contains details of the
parameters for the corresponding stored procedure, or stored query.
î It is used when output values or return values are required.
− Properties
î The Properties collection contains provider-specific properties.
Creating Objects
− To create an object of a Connection or Recordset, the following code is used:
Set con = Server.CreateObject("ADODB.Connection")
Set rs = Server.CreateObject("ADODB.Recordset")

− The CreateObject method of Server takes ProgId (the program ID) as a parameter.
− The ProgId is assigned by every component vendor to uniquely identify the COM object.

PDF created with pdfFactory Pro trial version www.pdffactory.com


4-1 ASP 7

Displaying Data from a Table


− The following code is used to retrieve data from a table and display it:
<%
Dim DB
Set DB = Server.CreateObject ("ADODB.Connection")
DB.Open "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" & Server.MapPath("db.mdb")
Dim RS
Set RS = Server.CreateObject ("ADODB.Recordset")
RS.Open "SELECT * FROM Students", DB
If RS.EOF And RS.BOF Then
Response.Write "There are 0 records."
Else
RS.MoveFirst
While Not RS.EOF
Response.Write RS.Fields ("FirstName")
Response.Write RS.Fields ("LastName")
Response.Write "<HR>"
RS.MoveNext
Wend
End If
%>
− Explanation of the code:
î Dim DB declares a variable for connection
î Set DB = Server.CreateObject ("ADODB.Connection") created an instance of a COM object
with ProgID ADODB.Connection, using the Set statement to assign this reference to the
variable, DB.
î DB.Open "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" & Server.MapPath("db.mdb")
A string expression that tells the connection object where to locate the database, and
more importantly, what type the database is
î Dim RS
Set RS = Server.CreateObject ("ADODB.Recordset")
RS.Open "SELECT * FROM Students", DB
Given an SQL statement, this line executes the query, and assigns the records returned to
our Recordset object.
î If RS.EOF And RS.BOF Then
Response.Write "There are 0 records."
In case your query returned no results, the Recordset.BOF (beginning of file) &
Recordset.EOF (end of file) are both True at the same time.
î Else
RS.MoveFirst
While Not RS.EOF
Response.Write RS.Fields ("FirstName")
Response.Write RS.Fields ("LastName")
Response.Write "<HR>"
RS.MoveNext
Wend
End If
%>
- RS.MoveFirst is a method that moves the record pointer to the First record.
- The While loop that iterates through all records of the Recordset, till RS.EOF is False.
- RS.Fields("FirstName") retrieves the value of the "FirstName" field of the current
record, and Response.Write writes it out to the page (Similarly for RS.Fields
("LastName")).
- The RS.MoveNext moves the record pointer to the next record.

Inserting Data into a Table


− The following code snippet can be used when adding a new record:

PDF created with pdfFactory Pro trial version www.pdffactory.com


4-1 ASP 8

DB.Mode = adModeReadWrite
RS.Open "Students", DB, adOpenStatic, adLockPessimistic
RS.AddNew
RS ("FirstName") = "Robbie"
RS ("LastName") = "Williams"
RS ("Email") = "robbiewilliams@musicmania.com"
RS ("DateOfBirth") = CDate("4 Feb, 1970")
RS.Update

− RS.AddNew adds a new, blank record to the database, following which you can set the fields
by assigning your data to the respective fields of the Recordset and finally executing the
Recordset.Update method to commit all changes to the record.

Updating Records
− The following code snippet can be used when updating a record:
RS.Open "SELECT * FROM Students WHERE FirstName = 'Archie'",
DB, adOpenStatic, adLockPessimistic
RS ("Email") = "archieandrews@riverdalehigh.com"
RS ("DateOfBirth") = CDate("12 Jul, 1982")
RS.Update

− Use a proper SQL statement to position the current pointer to the record that you wish to
update, modify the necessary fields by assigning new values to them, and execute the
RS.Update statement to write the changes back to the database.

Deleting Records
− Use the SQL DELETE statement to delete one or more records satisfying a particular
criterion.
DB.Open "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" & Server.MapPath("db.mdb")
DB.Execute ("DELETE * FROM Students WHERE FirstName = 'Archie'")

− Use the DELETE statement with utmost caution, as there’s no way to restore deleted
records, and also, in the absence of the WHERE clause, it deletes all of the records in the
table.

Cursors
− A cursor service decides the direction in which a database can be traversed.
− adOpenForwardOnly
î Returns a fast forward-only cursor (default).
î You can only move forward, not backward, through the Recordset object.
î Useful when you need to make only one pass through a Recordset object.
− adOpenKeyset
î Returns a keyset cursor, where you can move in any direction; first, last, forward,
backward, skip, or move to bookmark (if supported).
î You can see changes that others make to the records in the Recordset object, but you
can't see or change records added or deleted by others since you opened the Recordset
object.
î Use a keyset cursor for large record sets where you need to be able to scroll backward or
you need to change.
− adOpenDynamic
î Returns a dynamic cursor, exactly like a keyset cursor, except that you can see new
records that others add.
î It constantly checks constantly for updates and additions to the result set.
î Though they open quicker than a keyset cursor, they require the most resources of all
cursor types, and should not be used unless you need to see additions to the result set
while the Recordset object is open.

PDF created with pdfFactory Pro trial version www.pdffactory.com


4-1 ASP 9

− adOpenStatic
î Returns a static cursor, which is a fixed copy of a set of records.
î You cannot see any changes or inserts by others without querying the database again.
î Recordset objects with static cursors can be updated.
LockType
− The LockType argument tells ADO how to treat database locks.
− adLockReadOnly
î Read-only, i.e. you cannot alter the data at all.
− adLockPessimistic
î Records with pessimistic locking are unavailable to other users of your application.
î Pessimistic locks occur when the server delivers the record, and the record remains locked
until you close the Recordset object.
î You should avoid pessimistic locking in Web applications whenever possible.
− adLockOptimistic
î Optimistic locking locks records just before an update occurs, and unlocks them
immediately afterward.
î Other users can access data during the time you're updating the record, which means
they may potentially be viewing outdated data, so also, multiple users may
simultaneously try to update the same data, leading to problems.
î You should avoid optimistic locking in Web applications whenever possible.
− AdLockBatchOptimistic
î Optimistic batch locks act like optimistic locks, except they work for batch updates,
deferring immediate updates in favor of updating many records at one time rather than
updating each record immediately.
î The choice between immediate and batch updating depends on the level of interactivity
your application demands and how people expect to use the application.

COM COMPONENTS
− COM is the standard for the interface to objects.
− By definition, COM objects have only methods and properties; there are no other interfaces.
− Properties do not take any arguments and are usually used to describe or set the state of
an object.
− Methods can return values and take arguments (sometimes optional), and are most often
used to initiate an event within the object.
− Collections are objects that represent a set of objects, and all collections have predefined
methods and properties.
− A collection object has an Item method, a Count property, and a _NewEnum method.
− The Count property returns a LONG value that specifies how many objects are in the
collection.
− Item method returns the object in the set that is associated with that position.
− The _NewEnum method enables a programmer to iterate through the collection in a
For…Next statement.
For Each Object in Collection

Next Object

AdRotator Component
− It displays a different advertisement image each time a user visits or refreshes the page,
where each image is usually a hyperlink.
− A text file includes information about the images.
− The following ASP code is used:

PDF created with pdfFactory Pro trial version www.pdffactory.com


4-1 ASP 10

<%
url=Request.QueryString("url")
If url<>"" then Response.Redirect(url)
set adrotator=Server.CreateObject("MSWC.AdRotator")
response.write(adrotator.GetAdvertisement("textfile.txt")
%>
− The following is a sample content of the text file:
REDIRECT banners.asp
WIDTH 468
HEIGHT 60
BORDER 0
*
w3schools.gif
http://www.w3schools.com/
Visit W3Schools
80
microsoft.gif
http://www.microsoft.com/
Visit Microsoft
20
− This is the logic of the AdRotator component:
The REDIRECT keyword takes the name of the ASP file that contains the AdRotator
component.
Other properties for the AdRotator component can be specified as WIDTH HEIGHT BORDER
î The asterisk symbol (*) indicates the beginning of the details of the images to be
displayed within the AdRotator component.
î Every image description contains four lines: name of the image, hyperlink address, a text
string to be displayed as a tooltip, and the percentage of the number of hits for which that
image will be displayed.
î The code Server.CreateObject("MSWC.AdRotator") creates an AdRotator component.
î The variable url contains the name of the file specified along with the REDIRECT keyword.
î The method GetAdvertisement takes the text file containing image details as a parameter
and returns the HTML that displays the advertisement.
î The AdRotator component also takes the properties Border (size of border), Clickable
(whether advertisement is a hyperlink), and TargetFrame (frame within which to display
the advertisement).

PDF created with pdfFactory Pro trial version www.pdffactory.com

Vous aimerez peut-être aussi