Active Server Page - ASP in JavaScript 王金龍、陳彥錚 銘傳大學 資管系
Content u Introduction u Object Models u Request Object u Response Object u Server Object u Application and Session Objects u Installable Components for ASP
Introduction u Microsoft’s newest server-based technology for building dynamic interactive web pages u No compiler u Text editor u Browser independent u Object-oriented u Compatible to any ActiveX scripting u Transparent to users
ASP Usage Active Server Scripting Active Server Scripting
Complete ASP Program … Script which run in the browser Script which run in the server …
Server-side includes u u Include text files in pages u Virtual file addresses u u Physical file addresses u
Top Next Previous Top Next Previous … Form Use <% Response.Write(Request.Form("text1")); %>
Basic Statements u u Output a string ( more readable ) VarExpression% u or u Insert a string u u Redirect to the URL u
An ASP Example <% num=Request.Form("numOfHr"); msg="Welcome to My ASP Example!"; %> An ASP Example You are ! Iteration <% Response.Write(" "); } %>
Please input a number: Your Name: aspExample1.html
An ASP Example You are Yen-Cheng Chen ! Welcome to My ASP Example! Iteration 1 Iteration 2 Iteration 3 Iteration 4 Iteration 5 Source File in Web Client
Built-In ASP Objects u Request Object u To retrieve the values that the client browser passed to the server during an HTTP request. u Response Object u To send output to the client. u Server u Provide utility functions on the server.
Built-In ASP Objects (cont.) u Application u To share information among all users of a given application. (Like global variables) u Session u To store information needed for a particular user-session. (Like local variables) u ObjectContext u To commit or abort a transaction, managed by Microsoft Transaction Server (MTS).
Client Request Request Object Collection: Form QueryString ServerVariables Cookie ServerVariables Cookie ClientCertificate ClientCertificate Response Response Object Collection: Cookie (Properties) (methods) Server Server Object (method) Application Application Object (properties) (methods) Session Session Object (properties) (methods) Server
Request Object u Provide all the information about the user’s request to applications u Collection u A data store that can store values by linking each one to a unique key
Collections in Request Object u Five collections u QueryString u QueryString: HTTP query string (GET) u Form u Form: Form elements (POST) u ServerVariables u ServerVariables: HTTP and environment variables u Cookie u Cookie: Cookie sent from the browser u ClientCertificate u ClientCertificate: Certificate values (SSL: https) u Usage variable = Request.collectionName(“key”)
Properties and Methods u Properties u TotalBytes: Read-only. Specifies the total number of bytes the client is sending in the body of the request. u Methods BinaryRead( count ): Retrieves data sent to the server from the client as part of a POST request.
QueryString Collection: Get u The names and values of form are put into a query string u The amount of data can be sent is limited to around 1000 characters u Usage u variable = Request.QueryString(“name”)
queryTest.asp Query String Test ASP You are You are years old. queryTest.asp?name=Mickey+Mouse&age=50
Passing Name=Value Pairs with a Query String Sams Publishing Passing Name=Value Pairs with a Query String Sams Publishing Getting Name=Value Pairs with a Query String name = pub =
Form Collection: Post u The name and values of the form are encoded into the request header u Usage u variable = Request.Form(“name”)
the form text1: radio1: yes no select1: option 1 option 2 option 3 select2: (multiple) option 1M option 2M option 3M textarea1: formTest.html
Form Test ASP text1 radio1 select1 <%num=Request.Form("select2").Count; for (i=1;i select2 hidden1 textArea1 formTest.asp
ServerVariables Collections u Provide HTTP header that is sent by a client browser u To Retrieves the values of predetermined environment variables. u Usage u variable = Request.ServerVariables(“HeaderType”)
AUTH_TYPE = CONTENT_LENGTH = CONTENT_TYPE = GATEWAY_INTERFACE = LOGON_USER = PATH_INFO = PATH_TRANSLATED = QUERY_STRING = REMOTE_ADDR = REMOTE_HOST = REMOTE_METHOD = SCRIPT_MAP = SCRIPT_NAME = SERVER_NAME = SERVER_PORT = SERVER_PORT_SECURE = SERVER_PROTOCOL = SERVER_SOFTWARE = URL =
ALL_HTTPAll HTTP headers sent by the client. ALL_RAWAll 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_USERRaw authenticated user name. CERT_COOKIEUnique 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_KEYSIZENumber 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_ The value stored in the header HeaderName. HTTPSON : if the request came in through secure channel (SSL). OFF : Otherwise.
HTTPS_KEYSIZENumber of bits in Secure Sockets Layer connection key size. HTTPS_SECRETKEYSIZE Number of bits in server certificate private key. HTTPS_SERVER_ISSUERIssuer field of the server certificate. HTTPS_SERVER_SUBJECTSubject 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_INFOExtra path information as given by the client. PATH_TRANSLATEDA translated version of PATH_INFO (virtual-to-physical) QUERY_STRINGQuery information after ? in the HTTP request. REMOTE_ADDRThe IP address of the remote host making the request. REMOTE_HOSTThe name of the host making the request. REMOTE_USERUnmapped user-name string sent in by the User. REQUEST_METHODThe method used to make the request. SCRIPT_NAMEA virtual path to the script being executed. SERVER_NAMEThe server's host name, DNS alias, or IP address. SERVER_PORTThe port number to which the request was sent. SERVER_PORT_SECURE1 : If the request is on the secure port. 0 : Otherwise. SERVER_PROTOCOL The name and revision of the request information protocol. SERVER_SOFTWAREThe name and version of the server software. URLGives the base portion of the URL.
Cookie Collection u The cookie is a text file stored on the client u Use Request object to access the cookie u Read only u To change cookie: Use Response object u Usage u variable = Request.Cookies(“cookieVariable”)
Response Object u To send output to the client u Collection: Cookie u Properties u Buffer u CacheControl u Charset u ContentType u Expires u ExpiresAbsolute u isClientConnected u Pics u Status u Method AddHeader( name, value ) AppendToLog( string ) BinaryWrite( data ) u Clear() u End() u Flush() Redirect( url ) Write( variant )
Response Object: Classification u Insert information u Write(), BinaryWrite() u Send cookie: Cookie u Redirecting: Redirect() u Buffering the page u Buffer, Flush(), Clear(), End() u Setting the properties of a page u Expires, ExpiresAbsolute, CacheControl, ContentType, AddHeader, Status
Inserting Information Response.Write(“ string ”) u Insert a string into the HTML output u Convert the text to an appropriate character set u Response.BinaryWrite( data ) u Prevent the conversion
Sending Cookies u Response.Cookies(“CookieName”)=“data” u Response.Cookies(“CookieName”).Expires=“11/26/ :35:00” u Response.Cookies(“CookieName”).Domain=“/netnt.mcu.edu.tw/” u Response.Cookies(“CookieName”).Path=“/u99” u Response.Cookies(“CookieName”).Secure=True u Multiple Value Cookie <% Response.Cookies(“CookieName”)(“item1”)=“data1” Response.Cookies(“CookieName”)(“item2”)=“data2” %>
Redirecting the Browser u Refer users to alternative web pages u Redirection header u Tell the browser to go and get the information elsewhere u Usage u Response.Redirect(“URL”)
Buffering the Page u An extra degree of control over u When a client receives information u What they receive u Usage u Response.Buffer = True ’Default is false u Response.Flush() ’Send the current content u Response.Clear() ’Clear the current buffer u Response.End() ’Stop processing and send u When reach the end, the contents are sent
Server Object u The roof of the object model u Provides access to methods and properties on the server. u Most of these methods and properties serve as utility functions. u Property u ScriptTimeout: Amount of time a script can run u 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 path
ScriptTimeout Property u Define the delay before all scripts are terminated u Default = 90 seconds u Usage Server.ScriptTimout = nn;
HTMLEncode Method u Replace the angle-brackets with an escape sequence u Server Client ”) %>
URLEncode Method u Convert a string into URL-encoded form u Space + u Special chars %nn ”> 33 % 33%
MapPath Method u Provide file location information for use in scripts u Logical path Physical path u Usage u PhyPath = Server.MapPath(“/clipper”) u e:\clipper u /path: virtual directory u path: relative path
CreateObject Method u Invoke objects on the server u Extend the use of server components u Usage u Set obj = Server.CreateObject(“ProgId”) u Use the methods and access the properties of the object u IsObject( obj ) u Check if the object is created successfully
<% textfile = Server.MapPath("/app5")+"\\test1.html" fsObject = Server.CreateObject("Scripting.FileSystemObject") outStream= fsObject.CreateTextFile(textfile, true, false) myString = " File " outStream.WriteLine(mystring) now=new Date() myString = "The time is " + now.toLocaleString() outStream.WriteLine(mystring) outStream.WriteLine(" ") outStream.close() Response.Write(" My New Text File ")%>
Application Object u To share information among all users of a given application. u An ASP-based application is defined as all the.asp files in a virtual directory and its subdirectories. u Collections Contents : Contains all of the items that have been added to the Application. StaticObjects : Contains all of the objects added to the session with the tag.
Application Object (cont.) u Methods Lock : Prevents other clients from modifying Application object properties. Unlock : Allows other clients to modify Application object properties. u Events Application _ OnEnd : Occurs when the application quits Application _ OnStart : Occurs when a page is first referred. u Scripts for the preceding events are declared in the global.asa file.
Application Object u Usage Application.Lock() Application(“name”)=“value” Application.Unlock() u Event handles: u global.asa in the root directory of the virtual mapping function Application_OnStart() { … } function Application_OnEnd() { … }
Example - Application Object <% Application.Lock() Application("NumVisits") = Application("NumVisits") + 1 Application.Unlock() %>... This application page has been visited times! function Application_OnStart(){ Application(“NumVisits”)=0; } Global.asa
Application Object u Application Life u Start u The application starts the first time any client requests a document from that virtual mapping u End u The web server is stopped by the operating system
Please enter your name: Please enter your age: Please select which city your are living in: Seattle Denver Miami appTest.html
<% Application.Lock() Application("name") = ""+Request.Form("name") Application("age") = ""+Request.Form("age") Application("city") = ""+Request.Form("city") Application.Unlock() %> Hello, thank you The weather in is grey skies and plenty of rain. <% } else if (Application("city") = = "Denver") { %> The weather in is cold and snowy. The weather in is warm and sunny. appTest.asp
Session Object u Share data between different pages, but not between different clients u Session information is maintained on an individual client basis u Global to that client u A Session object is created when the client first makes a document request and destroyed 20 minutes after the last request.
Session Object u To store information needed for a particular user- session. u Variables stored in the Session object are not discarded when the user jumps between pages in the application u Collections Contents : Contains the items that you have added to the session with script commands. StaticObjects: Contains the objects created with the tag and given session scope.
u Properties u CodePage: Codepage used for symbol mapping. u LCID: Locale identifier. u SessionID: Session identification for this user. u Timeout: Timeout period for the session state, in minutes. u Methods u Abandon( ): Destroys a Session object and releases its resources. u Events (used in Global.asa) Session _ OnEnd: Session Timeout or abandoned u Session_OnStart: When server creates a new session u Usage: Session(“name”)=“value” Session Object (cont.)
SessionID Property u When store information in the Session object, the client is assigned a SessionID u Used to identify session u Actually be stored as a cookie with no expiry data set u Usage u Session.SessionID
Event Handler u global.asa … function Session_OnStart() { … ’first request a document } function Session_OnEnd() { …’Timeout or Abandon }
Summary u Object Models u Use Request Object to receive client's request. u Use Response Object to control the output to the client. u Use Server Object to access server utilities and objects. state u Use Application and Session Objects to maintain the web state.
Installable Components for ASP u Ad Rotator (AdRotator) u Ad Rotator (AdRotator): Automatically rotates advertisements displayed on a page according to a specified schedule. u BrowserCapabilities(BrowserType) u Browser Capabilities (BrowserType): Determines the capabilities, type, and version of Browser. u Database Access (ADO) u Database Access (ADO): Provides access to databases. u Content Linking (NextLink) u Content Linking (NextLink): Creates tables of contents. u File Access (FileSystemObject) u File Access (FileSystemObject): Provides access to file I/O. u Collaboration Data Objects for NTS Component u Collaboration Data Objects for NTS Component: Sends and receives messages to your Web page.
Installable Components for ASP (cont.) u Tools (Tools) u Tools (Tools): Enables you to add sophisticated functionality to your web pages. u MyInfo (MyInfo) u MyInfo (MyInfo): Keeps track of personal information. u Counters (Counters) u Counters (Counters): Creates, stores, increments, and retrieves individual counters. u Content Rotator (ContentRotator) u Content Rotator (ContentRotator): Automates the rotation of HTML content strings on a Web page. u Page Counter (PageCounter) u Page Counter (PageCounter): Counts and displays the number of times a Web page has been opened. u Permission Checker (PermissionChecker) u Permission Checker (PermissionChecker): Determines whether a Web user has been granted permissions to read a file.