Active Server Page - ASP Active Server Page - ASP in JavaScript in JavaScript 王王王 王王王 、 王王王王 王王王
Active Server Page - ASPActive Server Page - ASPin JavaScriptin JavaScript
王金龍、陳彥錚銘傳大學 資管系
ContentContent
Introduction Object Models Request Object Response Object Server Object Application and Session Objects Installable Components for ASP
IntroductionIntroduction Microsoft’s newest server-based
technology for building dynamic interactive web pages No compiler Text editor Browser independent Object-oriented Compatible to any ActiveX scripting Transparent to users
ASP UsageASP Usage
<%@language=JScript%>
<html> <head>
<title>Active Server Scripting</title>
</head>
<body>
<h3>Active Server Scripting </h3>
<% Response.Write("This is so cool!!!”)%>
</body>
</html>
Complete ASP ProgramComplete ASP Program <%@Language=JScript %> <HTML><HEAD> …</HEAD><BODY>
<% … ASP script which runs on the server … %><SCRIPT LANGUAGE=“JavaScript”>
Script which run in the browser</SCRIPT> <SCRIPT LANGUAGE=“JScript” RUNAT=Server>
Script which run in the server</SCRIPT><!-- #include … --><table> … </table>
<% … %> </BODY></HTML>
Server-side includesServer-side includes <!-- #include file=“include.txt” -->
Include text files in pages Virtual file addresses
<!-- #include virtual=“/u99/file.txt” -->
Physical file addresses <!-- #include file=“c:\inetpub\user99\file.txt” --> <!-- #include file=“file.txt” -->
<!-- menu.inc --><!-- menu.inc -->
<A HREF="top.htm">Top</A><BR><A HREF="top.htm">Top</A><BR><A HREF="next.htm">Next</A><BR><A HREF="next.htm">Next</A><BR><A HREF="previous.htm">Previous</A><BR><A HREF="previous.htm">Previous</A><BR><P><P>
…
<body>
<h3>Form Use </h3>
<!--#INCLUDE FILE="menu.inc"-->
<%
Response.Write(Request.Form("text1"));
%>
</body>
Basic StatementsBasic Statements <% Response.Write(“string”) %>
Output a string ( more readable ) <% = “string” %> or <%=VarExpression%VarExpression%>
Insert a string <%=Request.Form(“userName”)%>
<% Response.Redirect(“URL”) %> Redirect to the URL
<% // Some Comments %>
An ASP ExampleAn ASP Example<%@language=JScript%><% num=Request.Form("numOfHr");msg="Welcome to My ASP Example!";%><html><head><title>An ASP Example</title></head><body>You are <b><%=Request.Form("userName")%></b>!<br><%=msg%><hr><% for ( i=1; i<=num; i++) { %><font color=blue>Iteration <i><%=i%></i></font><%Response.Write("<hr width="+i*50+" align=left>");} %></body></html>
<html><body><form method="post" action="aspExample1.asp">Please input a number: <input type=text name="numOfHr" size=4><br>Your Name: <input type=text name="userName"><br><input type=submit></form> </body></html>
aspExample1.html
<html><head><title>An ASP Example</title></head><body>You are <b>Yen-Cheng Chen</b>!<br>Welcome to My ASP Example!<hr>
<font color=blue>Iteration <i>1</i></font><hr width=50 align=left><font color=blue>Iteration <i>2</i></font><hr width=100 align=left><font color=blue>Iteration <i>3</i></font><hr width=150 align=left><font color=blue>Iteration <i>4</i></font><hr width=200 align=left><font color=blue>Iteration <i>5</i></font><hr width=250 align=left></body></html>
Source File in Web ClientSource File in Web Client
Built-In ASP ObjectsBuilt-In ASP Objects
Request Object To retrieve the values that the client browser
passed to the server during an HTTP request.
Response Object To send output to the client.
Server Provide utility functions on the server.
Built-In ASP Objects (cont.)Built-In ASP Objects (cont.) Application
To share information among all users of a given application. (Like global variables)
Session To store information needed for a particular
user-session. (Like local variables)
ObjectContext To commit or abort a transaction, managed
by Microsoft Transaction Server (MTS).
Client
RequestRequest Object Collection: Form QueryStringForm QueryString
ServerVariables Cookie ServerVariables Cookie ClientCertificateClientCertificate
ResponseResponse Object Collection: CookieCookie
(Properties) (methods)
ServerServer Object(method)
ApplicationApplication Object(properties)(methods)
SessionSession Object(properties)(methods)
Server
Request ObjectRequest Object
Provide all the information about the user’s request to applications
Collection A data store that can store values by
linking each one to a unique key
Collections in Request ObjectCollections in Request Object
Five collections QueryStringQueryString: HTTP query string (GET) FormForm: Form elements (POST) ServerVariablesServerVariables: HTTP and environment variable
s CookieCookie: Cookie sent from the browser ClientCertificateClientCertificate: Certificate values (SSL: https)
Usagevariable = Request.collectionName(“key”)
Properties and MethodsProperties and Methods
Properties TotalBytes: Read-only. Specifies the total
number of bytes the client is sending in the body of the request.
Methods BinaryRead(count): Retrieves data sent to
the server from the client as part of a POST request.
QueryString Collection: GetQueryString Collection: Get
The names and values of form are put into a query string
The amount of data can be sent is limited to around 1000 characters
Usage variable = Request.QueryString(“name”)
queryTest.aspqueryTest.asp
<%@language=JScript%><html><head><title>Query String Test ASP</title></head><body>You are<font color=red><%=Request.QueryString("name")%></font><br>You are<font color=red><%=Request.QueryString("age")%></font>years old.</body></html>
queryTest.asp?name=Mickey+Mouse&age=50
<HTML><HEAD><TITLE></TITLE></HEAD><BODY><HTML><HEAD><TITLE></TITLE></HEAD><BODY>
<H3>Passing Name=Value Pairs with a Query String</H3><H3>Passing Name=Value Pairs with a Query String</H3><A NAME="product" HREF="<A NAME="product" HREF="list7_5.asp?name=dina&pub=list7_5.asp?name=dina&pub=samssams">Sams Publishing </A></BODY></HTML>">Sams Publishing </A></BODY></HTML>
<html> <head> <title></title> </head> <body>
<h3>Getting Name=Value Pairs with a Query String</h3>
<p>name = <%= Request.QueryString("name") %></p>
<p>pub = <% = Request.QueryString("pub") %> </p>
</body> </html>
Form Collection: PostForm Collection: Post
The name and values of the form are encoded into the request header
Usage variable = Request.Form(“name”)
<html><head> <title>the form</title></head><body><form name="form1" method=post action="formTest.asp">text1: <input type=text name="text1" size=20><br>radio1: <input type=radio name="radio1" value="yes">yes <input type=radio name="radio1" value="no">no<br>select1: <select name="select1"><option>option 1<option>option 2<option>option 3</select><br>select2: (multiple) <select name="select2" multiple><option>option 1M<option>option 2M<option>option 3M</select><br>textarea1: <textarea name="textArea1" cols=10 rows=5></textarea><br><input type=hidden name="hidden1" value="a hidden value"><input type=submit value="o.k.!"><input type=reset value="cancel"></form></body></html>
formTest.htmlformTest.html
<%@language=JScript%><html><head><title>Form Test ASP</title></head><body><table border=2><tr><td>text1</td><td><%=Request.Form("text1")%></td></tr><tr><td>radio1</td><td><%=Request.Form("radio1")%></td></tr><tr><td>select1</td><td><%=Request.Form("select1")%></td></tr><%num=Request.Form("select2").Count;for (i=1;i<=num;i++) { %><tr><td>select2</td><td><%=Request.Form("select2")(i)%></td></tr><% } %><tr><td>hidden1</td><td><%=Request.Form("hidden1")%></td></tr><tr><td>textArea1</td><td><%=Request.Form("textArea1")%></td></tr></table></body></html>
formTest.aspformTest.asp
ServerVariables CollectionsServerVariables Collections
Provide HTTP header that is sent by a client browser
To Retrieves the values of predetermined environment variables.
Usage variable = Request.ServerVariables(“HeaderTy
pe”)
AUTH_TYPE = <%= Request.ServerVariables("AUTH_TYPE") %><br> CONTENT_LENGTH = <% = Request.ServerVariables("CONTENT_LENGTH") %><br> CONTENT_TYPE = <% = Request.ServerVariables("CONTENT_TYPE") %><br> GATEWAY_INTERFACE =<% = Request.ServerVariables(“GATEWAY_INTERFACE”) %><br> LOGON_USER = <% = Request.ServerVariables("LOGON_USER") %><br> PATH_INFO = <% = Request.ServerVariables("PATH_INFO") %><br> PATH_TRANSLATED =<% = Request.ServerVariables("PATH_TRANSLATED") %><br> QUERY_STRING = <% = Request.ServerVariables("QUERY_STRING") %><br> REMOTE_ADDR = <% = Request.ServerVariables("REMOTE_ADDR") %><br> REMOTE_HOST = <% = Request.ServerVariables("REMOTE_HOST") %><br> REMOTE_METHOD = <% = Request.ServerVariables("REMOTE_METHOD") %><br> SCRIPT_MAP = <% = Request.ServerVariables("SCRIPT_MAP") %><br> SCRIPT_NAME = <% = Request.ServerVariables("SCRIPT_NAME") %><br> SERVER_NAME = <% = Request.ServerVariables("SERVER_NAME") %><br> SERVER_PORT = <% = Request.ServerVariables("SERVER_PORT") %><br> SERVER_PORT_SECURE = <%=Request.ServerVariables("SERVER_PORT_SECURE") %><br> SERVER_PROTOCOL = <% = Request.ServerVariables("SERVER_PROTOCOL") %><br> SERVER_SOFTWARE = <% = Request.ServerVariables("SERVER_SOFTWARE") %><br> URL = <% = Request.ServerVariables("URL") %><br>
ALL_HTTP All HTTP headers sent by the client. ALL_RAW All headers in the raw-form.APPL_MD_PATH The metabase path for the (WAM) Application for
the ISAPI DLL. APPL_PHYSICAL_PATH Retrieves the physical path corresponding to the metabase path. AUTH_PASSWORD The value entered in the client's authentication dialog.AUTH_TYPE The authentication method that the server uses to validate users.AUTH_USER Raw authenticated user name. CERT_COOKIE Unique ID for client certificate, Returned as a string.CERT_FLAGS bit0 is set to 1 if the client certificate is present.
bit1 is set to 1 if the client Certifying Authority is invalid.CERT_ISSUER Issuer field of the client certificate. CERT_KEYSIZE Number of bits in Secure Sockets Layer connection key size.CERT_SECRETKEYSIZE Number of bits in server certificate private key. CERT_SERIALNUMBER Serial number field of the client certificate. CERT_SERVER_ISSUER Issuer field of the server certificate. CERT_SERVER_SUBJECT Subject field of the server certificate. CERT_SUBJECT Subject field of the client certificate. CONTENT_LENGTH The length of the content as given by the client. CONTENT_TYPE The data type of the content.GATEWAY_INTERFACE The revision of the CGI specification used by the server.HTTP_<HeaderName> The value stored in the header HeaderName.HTTPS ON : if the request came in through secure channel (SSL).
OFF : Otherwise.
HTTPS_KEYSIZE Number of bits in Secure Sockets Layer connection key size.HTTPS_SECRETKEYSIZE Number of bits in server certificate private key.HTTPS_SERVER_ISSUER Issuer field of the server certificate. HTTPS_SERVER_SUBJECT Subject field of the server certificate. INSTANCE_ID The ID for the IIS instance in textual format.INSTANCE_META_PATH Metabase path for the IIS instance that responds to the request. LOCAL_ADDR Returns the Server Address on which the request came in. LOGON_USER The Windows NTR account that the user is logged into. PATH_INFO Extra path information as given by the client.PATH_TRANSLATED A translated version of PATH_INFO (virtual-to-physical)QUERY_STRING Query information after ? in the HTTP request. REMOTE_ADDR The IP address of the remote host making the request. REMOTE_HOST The name of the host making the request.REMOTE_USER Unmapped user-name string sent in by the User.REQUEST_METHOD The method used to make the request.SCRIPT_NAME A virtual path to the script being executed.SERVER_NAME The server's host name, DNS alias, or IP address.SERVER_PORT The port number to which the request was sent. SERVER_PORT_SECURE 1 : If the request is on the secure port. 0 : Otherwise.SERVER_PROTOCOL The name and revision of the request information protocol.SERVER_SOFTWARE The name and version of the server software.URL Gives the base portion of the URL.
Cookie CollectionCookie Collection
The cookie is a text file stored on the client
Use Request object to access the cookie Read only To change cookie: Use Response object
Usage variable = Request.Cookies(“cookieVariabl
e”)
Response ObjectResponse Object
To send output to the client Collection: Cookie Properties
Buffer CacheControl Charset ContentType Expires ExpiresAbsolute isClientConnected Pics Status
Method AddHeader(name, value) AppendToLog(string) BinaryWrite(data) Clear() End() Flush() Redirect(url) Write(variant)
Response Object: ClassificationResponse Object: Classification
Insert information Write(), BinaryWrite()
Send cookie: Cookie Redirecting: Redirect() Buffering the page
Buffer, Flush(), Clear(), End() Setting the properties of a page
Expires, ExpiresAbsolute, CacheControl, ContentType, AddHeader, Status
Inserting InformationInserting Information
Response.Write(“string”) Insert a string into the HTML output Convert the text to an appropriate characte
r set <% = “string” %> Response.BinaryWrite(data)
Prevent the conversion
Sending CookiesSending Cookies
Response.Cookies(“CookieName”)=“data” Response.Cookies(“CookieName”).Expires=“11/26/1197 17:35:00” Response.Cookies(“CookieName”).Domain=“/netnt.mcu.edu.tw/” Response.Cookies(“CookieName”).Path=“/u99” Response.Cookies(“CookieName”).Secure=True Multiple Value Cookie
<%
Response.Cookies(“CookieName”)(“item1”)=“data1”
Response.Cookies(“CookieName”)(“item2”)=“data2”
%>
Redirecting the BrowserRedirecting the Browser Refer users to alternative web pages Redirection header
Tell the browser to go and get the information elsewhere
Usage Response.Redirect(“URL”)
Buffering the PageBuffering the Page An extra degree of control over
When a client receives information What they receive
Usage Response.Buffer = True ’Default is false Response.Flush() ’Send the current
content Response.Clear() ’Clear the current
buffer Response.End() ’Stop processing and send When reach the end, the contents are sent
Server ObjectServer Object The roof of the object model
Provides access to methods and properties on the server.
Most of these methods and properties serve as utility functions.
Property ScriptTimeout: Amount of time a script can run
Method CreateObject(progID) Create an instance of an object HTMLEncode(string) HTML Encoding URLEncode(string) URL Encoding MapPath(path) Convert a virtual path to a physical p
ath
ScriptTimeout PropertyScriptTimeout Property
Define the delay before all scripts are terminated Default = 90 seconds
Usage Server.ScriptTimout = nn;
HTMLEncode MethodHTMLEncode Method
Replace the angle-brackets with an escape sequence
Server Client
<% = Server.HTMLEncode(“<Table>”) %>
<% = Server.HTMLEncode(“<%=Server.ScriptTimeout %\>”) %>
URLEncode MethodURLEncode Method Convert a string into URL-encoded form
Space +
Special chars %nn
<a href=“a1.asp?ans=<%server.urlencode(33%) %>”> 33 % </a>
<a href=“a1.asp?ans=33%25”> 33% </a>
MapPath MethodMapPath Method Provide file location information for use i
n scripts Logical path Physical path
Usage PhyPath = Server.MapPath(“/clipper”) e:\clipper /path: virtual directory path: relative path
CreateObject MethodCreateObject Method Invoke objects on the server
Extend the use of server components Usage
Set obj = Server.CreateObject(“ProgId”) Use the methods and access the propertie
s of the object IsObject( obj )
Check if the object is created successfully
<%@language=JScript%>
<% textfile = Server.MapPath("/app5")+"\\test1.html"
fsObject = Server.CreateObject("Scripting.FileSystemObject")
outStream= fsObject.CreateTextFile(textfile, true, false)
myString = "<HTML><HEAD><TITLE>File</TITLE></HEAD>"
outStream.WriteLine(mystring)
now=new Date()
myString = "The time is " + now.toLocaleString()
outStream.WriteLine(mystring)
outStream.WriteLine("</BODY></HTML>")
outStream.close()
Response.Write("<A HREF='test1.html'>My New Text File </A>")%>
Application ObjectApplication Object
To share information among all users of a given application.
An ASP-based application is defined as all the .asp files in a virtual directory and its subdirectories.
Collections Contents: Contains all of the items that have been added
to the Application. StaticObjects: Contains all of the objects added to the se
ssion with the <OBJECT> tag.
Application Object (cont.)Application Object (cont.)
Methods Lock: Prevents other clients from modifying Application
object properties. Unlock: Allows other clients to modify Application object
properties. Events
Application_OnEnd : Occurs when the application quits Application_OnStart : Occurs when a page is first refe
rred. Scripts for the preceding events are declared in t
he global.asa file.
Application ObjectApplication Object Usage
Application.Lock()Application(“name”)=“value”Application.Unlock()
Event handles: global.asa in the root directory of the virtual mappin
g function Application_OnStart() { … } function Application_OnEnd() { …
}
Example - Application ObjectExample - Application Object
<%@language=JScript%><%Application.Lock()Application("NumVisits") = Application("NumVisits") + 1Application.Unlock()%> ... This application page has been visited <%= Application("NumVisits") %> times!
<script language=Jscript runat=server>function Application_OnStart(){ Application(“NumVisits”)=0;}</script>
Global.asa
Application ObjectApplication Object
Application Life Start
The application starts the first time any client requests a document from that virtual mapping
End The web server is stopped by the operating
system
<FORM METHOD=POST NAME="Personal" ACTION="appTest.asp">
Please enter your name:
<input type=text size=20 name="name" value=""><br>
Please enter your age:
< input type=text size=5 name="age" value=""><br>
Please select which city your are living in:
<SELECT NAME="city" ><P>
<OPTION VALUE="Seattle">Seattle
<OPTION VALUE="Denver">Denver
<OPTION VALUE="Miami">Miami
</SELECT><br>
<INPUT TYPE=SUBMIT></FORM>
appTest.html
<%@language=JScript%><% Application.Lock()Application("name") = ""+Request.Form("name")Application("age") = ""+Request.Form("age")Application("city") = ""+Request.Form("city")Application.Unlock() %> <body> <h3>Hello <%= Application("name") %>, thank you</h3> <% if (Application("city") = = "Seattle") { %>The weather in <%= Application("city") %> is grey skies and plent
y of rain. <% }else if (Application("city") = = "Denver") { %> The weather in <%= Application("city") %> is cold and snowy.<% } else { %> The weather in <%= Application("city") %> is warm and sunny. <% } %> </p> <form name=“age” method=“POST” action="app2.asp"> <p><input type="SUBMIT" value="OK"> </p>
appTest.asp
Session ObjectSession Object Share data between different pages, but not
between different clients Session information is maintained on an individual client
basis Global to that client
A Session object is created when the client first makes a document request and destroyed 20 minutes after the last request.
Session ObjectSession Object
To store information needed for a particular user-session.
Variables stored in the Session object are not discarded when the user jumps between pages in the application
Collections Contents : Contains the items that you have added to the
session with script commands. StaticObjects: Contains the objects created with the <OB
JECT> tag and given session scope.
Properties CodePage: Codepage used for symbol mapping. LCID: Locale identifier. SessionID: Session identification for this user. Timeout: Timeout period for the session state, in minutes.
Methods Abandon( ): Destroys a Session object and releases its resources.
Events (used in Global.asa) Session_OnEnd: Session Timeout or abandoned Session_OnStart: When server creates a new session
Usage: Session(“name”)=“value”
Session Object (cont.)Session Object (cont.)
SessionID PropertySessionID Property
When store information in the Session object, the client is assigned a SessionID Used to identify session Actually be stored as a cookie with no expir
y data set Usage
Session.SessionID
Event HandlerEvent Handler
global.asa<%@language=JScript%>…function Session_OnStart() {… ’first request a document}function Session_OnEnd() {… ’Timeout or Abandon}
SummarySummary
Object Models Use Request Object to receive client's
request. Use Response Object to control the output
to the client. Use Server Object to access server utilities
and objects. Use Application and Session Objects to
maintain the web statestate.
Installable ComponentsInstallable Componentsfor ASPfor ASP
Ad Rotator (AdRotator)Ad Rotator (AdRotator): Automatically rotates advertisements displayed on a page according to a specified schedule.
BrowserBrowser CapabilitiesCapabilities (BrowserType)(BrowserType): Determines the capabilities, type, and version of Browser.
Database Access (ADO)Database Access (ADO): Provides access to databases. Content Linking (NextLink)Content Linking (NextLink): Creates tables of contents. File Access (FileSystemObject)File Access (FileSystemObject): Provides access to file I/
O. Collaboration Data Objects for NTS ComponentCollaboration Data Objects for NTS Component: Sends
and receives messages to your Web page.
Installable ComponentsInstallable Componentsfor ASP (cont.)for ASP (cont.)
Tools (Tools)Tools (Tools): Enables you to add sophisticated functionality to your web pages.
MyInfo (MyInfo)MyInfo (MyInfo): Keeps track of personal information. Counters (Counters)Counters (Counters): Creates, stores, increments, and retri
eves individual counters. Content Rotator (ContentRotator)Content Rotator (ContentRotator): Automates the rotation
of HTML content strings on a Web page. Page Counter (PageCounter)Page Counter (PageCounter): Counts and displays the nu
mber of times a Web page has been opened. Permission Checker (PermissionChecker)Permission Checker (PermissionChecker): Determines w
hether a Web user has been granted permissions to read a file.