Application Object
The Application object is an application-level object used to share information among all users and to persist data while the Web application is running.
Application properties:
Here's how:
The Application object has no built-in properties, but we can create its own properties.
<% Application("property name")=value%>
In fact, most Application variables are stored in the Contents collection. When you create a new Application variable, you actually add an item to the Contents collection. The following two scripts are equivalent:
<% Application("greeting")="hello!" %> or <% Application.contents("greeting")="hello!" Since the Application variables exist in the collection, if you want to display them all, we have many methods times, such as a For Each loop.
<%
For Each item IN Application.Contents
Response.write("<br>"&item&Application.Contents(item))
next
%>
Application method:
Application has only two methods: one is Lock and the other is Unlock. The Lock method is used to ensure that only one user can operate the Application at the same time. Unlock is used to cancel the restrictions of the Lock method. like:
<%
Application.Lock
Application("visitor_num")=Application("visitor_num")+1
Application.Unlock
%>
Application events:
1.Application_OnStart()
Fired when the event application starts.
2. Application_OnEnd()
This event is fired when the application ends.
These two event processes must be defined in the Global.asp file. Generally, the function for connecting data is defined in these two events and then placed in Global.asp. For example:
Sub Application_OnStart
Application("tt18_ConnectionString") = "driver={SQL
Server};server=jeff;uid=sa;pwd=;database=test"
End Sub
An array can be defined as an Application object, but this array can only be saved as an object, and its value cannot be retrieved using Application(0). You can define a temporary array to achieve this function. like:
<%
dimArray()
Array=Application("array")
for i = 0 to ubound(array)
Response.write Array(i)
next i
%>
To modify the Application object, you can also define a temporary array, assign the Application object to the array, then modify the elements of the array, and finally assign the array back to the Application object. like:
<%
dimArray()
Array=Application("array")
Array(0)="jeff"
Array(1)="zhu"
Application.lock
Application("array")=Array
Application.unlock
%>
ObjectContext object
This object is used to control the transaction processing of Active Server Pages. Transaction processing is managed by Microsoft Transaction Server (MTS).
The event
ObjectContext.OnTransactionAbort
is fired by the aborted transaction event and occurs after the script has completed processing.
ObjectContext.OnTransactionCommit
is triggered by a successful transaction event and occurs after the script has completed processing.
The method
ObjectContext.SetAbort
explicitly aborts a transaction.
ObjectContext.SetComplete
overrides any previous call to the ObjectContext.SetAbort method.
Request object
The Request object is used to accept all information in all requests sent from the browser to your server.
Collection
Request.ClientCertificate(key[SubField])
A collection of information about all client certificates. For Key, the collection has the following keywords:
Subject
The subject of the certificate. Contains all information about certificate receipts. Can be used with all subdomain suffixes.
Issuer
The issuer of the certificate. Contains all information about certificate verification. Can be used with all subdomain suffixes except CN.
VadidFrom
The date the certificate was issued. Use VBScript format.
ValidUntil
The certificate is no longer valid.
SerialNumber
Contains the serial number of the certificate.
Certificate
A binary stream containing the entire certificate contents, using ASN.1 format.
For SubField, Subject and Issuer keywords can have the following subdomain suffix: (for example: SubjectOU or IssuerL)
C
Country of origin.
O
Company or organization name.
OU
organizational unit.
EN
The user's regular name.
L
Partially.
S
State (or province).
T
The title of the person or company.
GN
given name.
I
initial.
When the file cervbs.inc (used by VBScript) or cerjavas.inc (used by Jscript) is included in your Active Server Page using the #INCLUDE directive, the following two flags can be used:
ceCertPresent
Indicates whether the client certificate exists, its value is TRUE or FALSE.
ceUnrecongnizedIssure
Indicates whether the issuer of the last certificate in the list is unknown, its value is TRUE or FALSE.
Request.Cookies(Cookie[(key).Attribute])
Collection of Cookies. Allow browser cookies to be obtained. Cookie indicates which cookie to return. Key is used to return the Cookie value with a certain keyword from the Cookie dictionary. For Attribute, you can use the attribute HasKeys to determine whether a cookie has subkeys. The value of HasKeys is TRUE or FALSE.
Request.Form(Parameter)[(Index).Count]
fills in the collection of all data in the HTML form. Parameter is the name of an element in an HTML form. Index is used when a parameter has more than one value (for example, when using the MULTIPLE attribute in <SELECT>). When a parameter has multiple values, Count specifies the number of multiple values.
Request.QueryString(Varible)[(Index).Count]
The collection of all values of the query string. Variable is the name of a variable in the query string. Index is used when a variable has more than one value. When a parameter has multiple values, Count specifies the number of values.
Request.ServerVaribles (Server Environment Variable)
A collection of environment variables. Allows reading HTTP headers. You can read any header information by using the HTTP_ prefix. For example, HTTP_USER_AGENT accepts the Client-Agent HTTP header (browser type). Otherwise, you can obtain any environment information using the variables shown in the table below.
ALL_HTTP
All HTTP headers sent by the client and its results are prefixed with HTTP_.
ALL_RAW
All HTTP headers sent by the client have the same result as when sent by the client, without the prefix HTTP_
APPL_MD_PATH
The application's metabase path.
APPL_PHYSICAL_PATH
The physical path corresponding to the application metabase path.
AUTH_PASSWORD
The password entered by the customer in the password dialog box when using basic authentication mode.
AUTH_TYPE
This is the authentication method used by the server to verify users when they access protected scripts.
AUTH_USER
Username for verification.
CERT_COOKIE
Unique client certificate ID number.
CERT_FLAG
Client certificate flag. If there is a client certificate, bit0 is 0. If the client certificate verification is invalid, bit1 is set to 1.
CERT_ISSUER
The issuer field in the user's certificate.
CERT_KEYSIZE
The number of bits of the Secure Socket Layer connection keyword, such as 128.
CERT_SECRETKEYSIZE
The number of digits in the private key that the server verifies. Such as 1024.
CERT_SERIALNUMBER
The serial number field of the client certificate.
CERT_SERVER_ISSUER
The issuer field of the server certificate
CERT_SERVER_SUBJECT
The subject field of the server certificate.
CERT_SUBJECT
The subject field of the client certificate.
CONTENT_LENGTH
The length of content sent by the client.
CONTENT_TYPE
The form content sent by the customer or the data type of HTTP PUT.
GATEWAY_INTERFACE
The gateway interface used by the server.
HTTPS
Returns ON if the request went over a secure channel (SSL). If the request comes from a non-secure channel, return OFF.
HTTPS_KEYSIZE
The number of bits of the Secure Socket Layer connection keyword, such as 128.
HTTPS_SECRETKEYSIZE
The number of digits in the private key that the server verifies. Such as 1024.
HTTPS_SERVER_ISSUER
The issuer field of the server certificate.
HTTPS_SERVER_SUBJECT
The subject field of the server certificate.
INSTANCE_ID
The ID number of the IIS instance.
INSTANCE_META_PATH
The metabase path of the IIS instance that responded to the request.
LOCAL_ADDR
Returns the address of the server that accepted the request.
LOGON_USER
The user logs in to Windows NT with the account
PATH_INFO
Path information provided by the client.
PATH_TRANSLATED
The path obtained by mapping from virtual to physical.
QUERY_STRING
Query string content.
REMOTE_ADDR
The IP address of the remote host making the request.
REMOTE_HOST
The name of the remote host from which the request was made.
REQUEST_METHOD
Method of making a request. Such as GET, HEAD, POST, etc.
SCRIPT_NAME
The name of the executed script.
SERVER_NAME
The hostname, DNS address, or IP address of the server.
SERVER_PORT
The server port number that accepts requests.
SERVER_PORT_SECURE
If the server port that accepts the request is a secure port, it is 1, otherwise it is 0.
SERVER_PROTOCOL
The name and version of the protocol used by the server.
SERVER_SOFTWARE
The name and version of the server software that answers requests and runs the gateway.
URL
Provide the basic part of the URL.
The method
Request.BinaryRead(Count)
receives the unprocessed content of an HTML form. When this method is called, Count indicates how many bytes to receive. After calling this method, Count indicates how many bytes were actually received.
Property
Request.TotalBytesThe
length of the query body, in bytes
Response object
The Response object is used to send data to the client browser. Users can use this object to send server data to the client browser in HTML format. It and Request form a pair of objects for receiving and sending data. This is also The basis for achieving dynamics. Its commonly used properties and methods are introduced below.
1. Buffer attribute This attribute is used to specify whether a buffer should be used when outputting the page. The default value is False. When it is True, the results will not be output to the browser until the entire Active Server Page is executed. like:
<%Response.Buffer=True%>
<html>
<Head>
<title>Buffer Example</title>
</head>
<body>
<%
for i=1 to 500
response.write(i & "<br>")
next
%>
</body>
</html>
When this page is executed, all the contents of the entire homepage will be displayed on the browser at the same time, and the homepage will be stored in the cache until the script execution is completed.
2. Expires attribute This attribute is used to set the length of time (in minutes) that the browser caches the page, and must be refreshed on the server side. With the following settings:
<%Response.Expires=0%>
By adding this line of code to the ASP file, each request is required to refresh the page, because the page will expire as soon as the Response is received.
3. Write method This method sends data to the client browser, such as:
<%Response.write "Hello,world!"%>
4. Redirect method This method allows the browser to relocate to another URL. In this way, when the client makes a Web request, the client's browser type has been determined and the client is relocated to the corresponding page. like:
<html>
<head>
<title>Redirect example</title>
</head>
<body>
<form aciton="formjump.asp" method="post">
<select name="wheretogo">
<option selected value="fun">Fun</option>
<option value="news">News</option>
<option value="sample">Sample</option>
</select>
<input type=submit name="jump" value="Jump">
</form>
</body>
</html>
The above is the submitted form, and the following is the file formjump.asp that processes the form:
<%response.buff=true%>
<html>
<head>
<title>Redirect example</title>
</head>
<body>
<%
thisurl=" http://www.tinyu.com/ ";
where=Request.form("wheretogo")
Select Case where
case "fun"
response.redirect thisurl & "/fun/default.asp"
case "news"
response.redirect thisurl & "/news/default.asp"
case "sample"
response.redirect thisurl & "/sample/default.asp"
End Select
%>
</body>
<html>
In this example, when the user makes a selection, he presses the "Jump" button to submit the form. After receiving the application, the server calls formjump.asp to determine and locate the corresponding URL. However, one thing to note here is that the HTTP header has been written to the client's browser. Any modification of the HTTP header must be done before writing the page content. When encountering this problem, you can do the following:
At the beginning of the file after <@ Language=..> write:
Response.Buffer=True
Decide at the end:
Response.Flush
Flush here is a method of Response, which can only be used when the Buffer property is set to True, otherwise a run mode error will be generated. Another Clear method is also used to clear cached pages. It can also be used when the Buffer property is set to True.
5. End method This method is used to tell Active Server to stop processing ASP files when encountering this method. If the Buffer property of the Response object is set to True, the End method will send the contents of the cache to the client and clear the buffer. Therefore, to cancel all output to clients, you can first clear the buffer and then use the End method. like:
<%
Response.buffer=true
On error resume next
Err.clear
if Err.number<>0 then
Response.Clear
Response.End
end if
%>
Server Object:
The Server object provides access to methods and properties on the server. Most of these methods and properties serve as utility functions.
Syntax
Server.property|method
property
ScriptTimeout:
The ScriptTimeout property specifies the maximum amount of time a script can run before ending. When working with server components, the timeout limit will no longer take effect.
Syntax Server.ScriptTimeout = NumSeconds
Parameter NumSeconds
Specifies the maximum number of seconds a script can run before being terminated by the server. The default value is 90 seconds.
Note You can set a default ScriptTimeout value for a Web service or Web server by using the AspScriptTimeout property in the metabase. The ScriptTimeout property cannot be set less than the value specified in the metabase. For example, if NumSeconds is set to 10 and the metabase setting contains the default value of 90 seconds, the script times out after 90 seconds. But if NumSeconds is set to 100, the script times out after 100 seconds.
For more information about using the metabase, see About the Metabase.
Example The following example times out if the server takes more than 100 seconds to process the script.
<% Server.ScriptTimeout = 100 %>
The following example gets the current value of the ScriptTimeout property and stores it in the variable TimeOut.
<% TimeOut = Server.ScriptTimeout %>
Method
CreateObject
The CreateObject method creates an instance of the server component. If the component executes the OnStartPage and OnEndPage methods, the OnStartPage method will be called at this time. For more information about server components, see Installable ASP Components.
Syntax Server.CreateObject( progID )
Parameter progID specifies the type of object to be created. The format of progID is [Vendor.] component[.Version].
Note By default, objects created by the Server.CreateObject method have page scope. This means that the server will automatically destroy these objects after the current ASP page is processed. To create a session or application scoped object, you can use the <OBJECT> tag and set the SCOPE attribute of SESSION or APPLICATION, or you can store the object in session and application variables.
For example, in the script shown below, when the Session object is destroyed, that is, when the conversation times out or the Abandon method is called, the objects stored in the session variables will also be destroyed.
<% Set Session("ad") = Server.CreateObject("MSWC.AdRotator")%>
You can destroy an object by setting the variable to Nothing or a new value, as shown below. The first example releases the ad object, and the second example replaces ad with a string.
<% Session ("ad") = Nothing %>
<% Session ("ad") = " Other Valum " %>
An object instance with the same name as a built-in object cannot be created. For example, the following script will return an error.
<% Set Response = Server.CreateObject("Response") %>
Example <% Set MyAd = Server.CreateObject("MSWC.AdRotator") %>
The above example creates an MSWC.AdRotator server component named MyAd. The MSWC.AdRotator component can be used to automatically rotate ads on Web pages.
For more information about server components, see Creating Components for ASP.
HTMLEncode The HTMLEncode method applies HTML encoding to the specified string.
Syntax Server.HTMLEncode(string)
Parameter string specifies the string to be encoded.
Sample script <%= Server.HTMLEncode("The paragraph tag: <P>") %>
Output The paragraph tag: <P>
Note that the above output will be displayed by the web browser as The paragraph tag: <P>If you look at the source file or open a Web page in text mode and you can see the encoded HTML.
MapPath
The MapPath method maps the specified relative or virtual path to the corresponding physical directory on the server.
grammar
Server.MapPath(Path)
parameter
Path
Specify a relative or virtual path to the physical directory to be mapped. If Path begins with a forward slash (/) or backslash (), the MapPath method treats Path as a complete virtual path when returning the path. If Path does not begin with a slash, the MapPath method returns a path relative to an existing path in the .asp file.
Comment
The MapPath method does not support relative path syntax (.) or (..). For example, the following relative path ../MyDir/MyFile.txt returns an error.
The MapPath method does not check whether the returned path is correct or exists on the server.
Because the MapPath method only maps paths regardless of whether the specified directory exists, you can first use the MapPath method to map the path to the physical directory structure and then pass it to the component that creates the specified directory or file on the server.
Example For the following example, the file data.txt and the test.asp file containing the following script are located in the directory C:InetpubWwwrootScript. The C:InetpubWwwroot directory is set as the server's home directory.
The following example uses the server variable PATH_INFO to map the physical path to the current file. script
<%= server.mappath(Request.ServerVariables("PATH_INFO"))%><BR>
Output
c:inetpubwwwrootscripttest.asp<BR>
Because the path parameters in the following examples do not begin with a slash character, they are relatively mapped to the current directory, in this case C:InetpubWwwrootScript . script
<%= server.mappath("data.txt")%><BR>
<%= server.mappath("script/data.txt")%><BR>
Output
c:inetpubwwwrootscriptdata.txt<BR>
c:inetpubwwwrootscriptscriptdata.txt<BR>
The next two examples use the slash character to specify that the returned path should be treated as the full virtual path on the server. script
<%= server.mappath("/script/data.txt")%><BR>
<%= server.mappath("script")%><BR>
Output
c:inetpubscriptdata.txt<BR>
c:inetpubscript<BR>
The following example shows how to use forward slash (/) or backslash () to return the physical path of the host directory. script
<%= server.mappath("/")%><BR>
<%= server.mappath("")%><BR>
Output
c:inetpubwwwroot<BR>
c:inetpubwwwroot<BR>
URLEncode
The URLEncode method applies URL encoding rules, including escape characters, to the specified string.
grammar
Server.URLEncode(string)
parameter
String specifies the string to encode.
Sample script <%Response.Write(Server.URLEncode(" http://www.tinyu.com ";)) %>
output http%3A%2F%2Fwww%2Etinyu%2Ecom
The Session object
Session actually refers to the period of time from when a visitor arrives at a specific home page to when he leaves. Each visitor will get a separate Session. In a web application, when a user accesses the application, Session type variables can be used by the user to share data in all pages of the web application; if another user also accesses the web application at the same time, he also has his own Session. Variables, but information cannot be shared between two users through Session variables, while changes of the Application type can share information in all pages between multiple users of the site.
1. SessionID attribute This attribute returns the unique identifier of the current session and assigns a different number to each Session.
I once encountered the problem of user control during the development process. The function it wants to achieve is that for a module of a certain website, when a member is viewing this module after logging in, and another person logs in with the same member name, he cannot browse this module. In other words, only one person with one member name can browse this module at the same time. I implemented the control by using the member name (assumed to be UserID, unique) and SessionID. When a member logs in, give the member a Session to record the login status, such as: Session("Status")="Logged", and write the member's Session.SessionID into the database. When he wants to browse this module, he first determines whether he is logged in. If he is already logged in, he determines whether his Session ID is the same as that recorded in the database. If he is different, he cannot access it. In this way, when another user logs in with the same member name, the new SessionID is recorded in the database, and the former cannot pass the check when accessing this module. This enables only one person with one member name to browse a certain module at the same time. This function has a special effect on some paid websites. It prevents the problem of one member name being browsed by multiple people and protects the interests of the company.
2. TimeOut attribute This attribute is used to define the time limit of the user Session object. If the user does not refresh the web page within the specified time, the Session object will be terminated. The general default is 20 minutes.
3. Abandon method This method is the only method of the Session object. It can clear the Session object and is used to eliminate the user's Session object and release the resources it occupies. For example: <% Session.Abandon %>
4. Session_OnStart and Session_OnEnd events are the same as Application. The Session_OnStart event is triggered every time the object's routine is started, and then the processing of the Session_Onstart event is run. That is, when the server receives an HTTP request for the URL in the application, this event is triggered and a Session object is established. In the same way, this event must also be set in the Global.asa file.
When the Session.Abandon method is called or there is no refresh within the TimeOut time, this will trigger the Session_OnEnd event and then execute the script inside. Session variables are associated with specific users. Session variables assigned to a certain user are completely independent from Session variables of other users and will not affect each other.
Session applies a column:
Like Application, an array defined as Session type can only treat the entire array as an object, and users cannot directly change the value of an element in the Session array. In order to create a Session array, you need to first define an ordinary array, assign an initial value to each element of it, and finally define it as a Session array. like:
<%
dimarray()
array=array("李","明","男")
Session("info")=array
Response.write Session("info")(0) &"-"
Response.write Session("info")(1) &"-"
Response.write Session("info")(2) &"<br>"
%>
<hr>
<%
array(0)="day"
array(1)="Yu"
array(2)="Male"
Session("info")=array
Response.write Session("info")(0) & "-"
Response.write Session("info")(1) & "-"
Response.write Session("info")(2) & "<br>"
%>