Create a three-tier ASP Application

Source: Internet
Author: User
Tags dsn

I. What are the disadvantages of ASP applications with two-layer structures?
In Browser/Server application development, Microsoft's IIS/ASP has become popular with its powerful functions, excellent scalability, and consistency with other Microsoft products. It enables a programmer with VB/VC experience to quickly become a Web programmer and develop seemingly very professional applications. However, ASP has a natural drawback: ASP code and HTML code are mixed together. ASP programmers need to consider dealing with databases and how to cooperate with HTML, sometimes you need to use ASP to directly generate HTML code. The result is that when the program logic is complex enough ,. the asp source file is very long. In addition, whether the user interface is changed or the business logic is changed (for example, in the examination system, the standard for "pass" may pass from 60 to the first 100. asp files are modified, while business logic changes may require many files to be modified.

 

2. Three-layer structure concept
The same problem exists in traditional Client/Server applications. Multi-layer applications are based on the summary of the C/S structure, it has also been extended to the B/S application development field. The application is divided into three layers (more layers are available, but the most common layer is the user interface layer, business logic layer, and database layer. The user interface layer is responsible for processing user input and output to the user, but is not responsible for interpreting the meaning (for efficiency reasons, it may verify validity before the user input is transferred up ), this layer is usually developed using front-end tools (such as VB, VC, and ASP). The business logic layer is the bond between the upper and lower layers, which establishes the actual database connection, generate an SQL statement based on your request to retrieve or update the database and return the result to the client. This layer usually exists in the form of a dynamic link library and is registered to the server Registry) the interface that it communicates with the client conforms to a specific component standard (such as COM and CORBA) and can be developed using any tool that supports this standard; the database layer stores and retrieves data. With this structure, the above problem can be solved: in the case of passing standards in the examination system, call the GetQualifiedList function where the client needs to display the qualified personnel list, as for how to write this function, how to deal with the database, and what database to access, it has nothing to do with it (you must have had such experience, SQL statements that run well on a database system are sometimes changed to another database system and must be modified). The GetQualifiedList function is implemented in the intermediate layer DLL, if you have changed the definition of "qualified", you only need to modify this function. As long as the entry parameters and returned content of this function remain unchanged, no changes are required on the client side. Here, we see the advantages of encapsulation, one of the features of object-oriented programming, which is especially useful for developing large applications-we can divide developers into two groups, one group is responsible for developing the interface layer, and the other group is responsible for developing the business logic layer. Both parties only need to develop the function interface in parallel according to the previously agreed function interface, instead of having to do the same as before, the subsequent work can only begin after the previous work is completed. Of course, such a development model requires good project coordination and documentation support.

 

You may ask, isn't it the same purpose if I include these functions in a separate file and then include them in the place where I want to call them? First, this method is inefficient. No matter how many files you distribute these functions to, when you need to call one of them, it will always contain some functions that are not actually needed, this will undoubtedly increase the burden on the server, especially for Web applications with high server performance requirements. While DLL is only transferred to the memory when needed and only to the required functions, and multiple application instances can share the same DLL instance; second, imagine an employee, there are 20 attributes (employee ID, name, age, gender ......), if a job number is specified, all information about the employee must be returned. If you use a function, you can define only 20 global variables, change the value of these variables in the function, or define a function with 20 by reference parameters. Obviously, the first method is very troublesome. Once an attribute is added, the latter method needs to change the function interface. An object contains both Member methods (functions and processes) and member attributes. If we use the object method, we only need to change the attributes of the object in the function, and can directly reference the changed object attribute value outside the function. This method is similar to the first method, but 1. attribute values do not need to be described one by one outside the function; 2. these attribute values only belong to objects. Code irrelevant to objects does not unintentionally change the attribute values. 3. once an object is released, these values are released together.

 

3. How to develop a three-layer ASP Application
ASP has good scalability. When we access the database, we use the time ADO object. when accessing files, we use the File System Object (FSO ), in fact, the program is already a three-tier application, but it is realized by using the built-in object. All these objects follow the COM/ActiveX interface, so we must also follow this interface for self-developed objects. Next, we will take the "qualified" Standard mentioned above as an example to demonstrate how to create your own three-tier ASP application.

 

1. Create the following database tables in the database system:

 

Employee: EMPLID char (5) not null,
Name char (10) not null,
Gender char (1) not null,
Score int not null
This table stores employee information and test scores. For the sake of simplicity, This table contains only three items: employee ID, name, and Gender. There is only one test and EMPLID is the primary key.

 

2. Create a dynamic link library
Start VB (Here we use VB as an example, you can use any development tool you like to support ActiveX interfaces), create a project, the project type is ActiveX DLL. Create a new class in the project named "Employee. You can add attributes and methods to the Class visually in Class Builder or manually edit them. First, add the EMPLID attribute as follows:
Private msEMPLID as string
Property Let EMPLID (sEMPLID as string)
MsEMPLID = sEMPLID
End Property
Property Get EMPLID () as string
EMPLID = msEMPLID
End Property

 

Generally, each Property should have two methods: Property Let and Property Get. They are called when assigning values to the Property and reading the Property value respectively. If an attribute is assigned only and never read (this often happens on the attribute of the primary key of the corresponding database table), the Property Get method can be omitted. The Property Let method cannot be omitted. You can create three attributes: Name, Gender, and Score based on the above program. Create the following method:

 

Public Sub Create (EMPLID as string)
Dim conn as new Connection
Dim rs as new Recordset
Dim SQL as string
"Suppose that you create a DSN in the control panel, the connectionstring property
"Can also be dsn-less string
Conn. ConnectionString = "dsn = dsnname; uid = username; password = pwd"
Conn. open
SQL = "select * from Employee where EMPLID =" "& EMPLID &"""
With rs
. Open SQL, conn, 1, 3
If. eof and. bof then
Exit sub
Else
MsEMPLID = trim (. Fields ("EMPLID "))
MsName = trim (. Fields ("Name "))
MsGender = trim (. Fields ("Gender "))
MsScore =. Fields ("Score ")
End if
. Close
End
Set rs = nothing
Conn. close
Set conn = nothing
End Sub
Here, we create an Employee object based on the EMPLID. Note that the value in the database is assigned to three private variables instead of directly assigning values to attributes. If you perform one-step debugging, you will find that, if you assign a value to msEMPLID, the Property Let EMPLID is called, that is, the attribute is assigned.
Create another class Employees and add the following method:
Private colQualifiedList as new Collection
Private mnCurrentIndex as integer
Public Sub GetQualifiedList ()
Dim conn as new Connection
Dim rs as new Recordset
Dim SQL as string
"Suppose that you create a DSN in the control panel, the connectionstring property
"Can also be dsn-less string
Conn. ConnectionString = "dsn = dsnname; uid = username; password = pwd"
Conn. open
SQL = "select EMPLID from Employee where Score> = 60 order by Score desc"
With rs
. Open SQL, conn, 1, 3
If. eof and. bof then
Exit sub
Else
Do while not. eof
Dim oEmployee as new Employee
OEmployee. Create trim (. Fields ("EMPLID "))
ColQualifiedList. Add oEmployee
Set oEmployee = nothing
Loop
End if
. Close
End
Set rs = nothing
Conn. close
Set conn = nothing
End Sub
First, pay attention to the syntax dim oEmployee as new Employee for creating class instances in VB. Later we will see that the syntax for creating class instances in ASP is different. This method retrieves the Employee ID with a score greater than or equal to 60, creates an Employee object accordingly, and then adds the object to a private set object. The following two functions traverse the elements in the Set:
Public Function GetFirst () as Employee
If colQualifiedList. count> 0 then
MnCurrentIndex = 1
Set GetFirst = colQualifiedList. Item (1)
Else
Set GetFirst = nothing
End if
End Function
Public Function GetNext () as Employee
MnCurrentIndex = mnCurrentIndex + 1
If mnCurrentIndex> colQualifiedList. count then
Set GetNext = nothing
Else
Set GetNext = colQualifiedList. Item (mnCurrentIndex)
End if
End Function
Maybe you will say, why not declare the set Public so that it can be directly referenced in ASP? Indeed, this works, and programming is easier to implement. However, this destroys the encapsulation principle. Because the format of data storage is completely at the business logic layer, it has nothing to do with the user interface layer. Assume that one day you give up the design of using a set to store data for every reason, instead of using arrays or Recordset for storage, you only need to modify the GetFirst and GetNext functions. The user interface layer does not need to be modified.
After the class File is created, save the project File as test. vbp and select the Make test. dll option under the File menu to compile it.
3. register the dynamic link library
Start Microsoft Transaction Server (Start -- Windows NT Optionpack4 -- Internet Information Server -- Internet Service Manager) on the Web Server, and Start Microsoft Transaction Server -- Computer -- My Computer -- Package Installed, right-click and choose New -- Package -- Create Empty Package. Enter the Package name Test (here Test is an optional name and does not have to be the same as the DLL name ), OK-Interactive User-the current Logon user -- Finish. Double-click Test -- Component, right-click Component-New-Component-Install New component (s) -- Add File, and select the DLL File you just compiled, MTS will find that the DLL contains two classes: Employee and Employees. So far, DLL registration is complete.

 

4. Compile an ASP program
<HTML> <Body>
<P> Qualified Employee List </p>
<Table border = 1 cellspacing = 0 cellpadding = 0>
<Tr>
<Td> Employee ID </td>
<Td> Name </td>
<Td> Gender </td>
<Td> Score </td>
</Tr>
<%
Set oEmployees = server. createobject ("Test. Employees ")
OEmployees. GetQualifiedList
Set oEmployee = oEmployees. GetFirst ()
Do while not oEmployee is nothing
%>
<Tr>
<Td> <% = oEmployee. EMPLID %> </td>
<Td> <% = oEmployee. Name %> </td>
<Td> <% = oEmployee. Gender %> </td>
<Td> <% = oEmployee. Score %> </td>
</Tr>
<%
Set oEmployee = oEmployees. GetNext ()
Loop
%>
</Table>
</Body> Note that the syntax set oEmployees = server is used to create a class instance in ASP. createobject ("Test. employees "), where Test is the DLL name and Employees is the class name. Of course, if the return value of a function is an object, it is similar to set oEmployee = oEmployees. the GetFirst () syntax is also acceptable.
So far, a complete three-tier application has been completed. Let's take a look at the following. If we change the definition of "qualified" to: only when the score reaches the top 100 is considered qualified, the program needs to make those changes. In fact, if your database system is SQL Server, you only need to change the SQL statement:
SQL = "select top 100 EMPLID from Employee order by Score desc" is enough. Even for cross-database system compatibility, we only need to modify GetQualifiedList as follows:

 

......
SQL = "select EMPLID from Employee order by Score desc"
With rs
. Open SQL, conn, 1, 3
If. eof and. bof then
Exit sub
Else
I = 1
Do while (not. eof) and (I <= 100)
Dim oEmployee as new Employee
OEmployee. Create trim (. Fields ("EMPLID "))
ColQualifiedList. Add oEmployee
Set oEmployee = nothing
I = I + 1
Loop
End if
. Close
End
...

 

Then, recompile the DLL and register it. The ASP program does not need to be modified at all.

 

Iv. Instructions and precautions
1. because this example is relatively simple, there can be no Create method in the Employee class, and in the Employees class, all the information of the Employee (Employee ID, name, gender, score) are read and assigned to the attributes of the Employee object. However, in practical applications, when the attributes of the Employee object increase or the number of tables increases and the relationship between tables becomes more complex, the method shown in this article is more effective and the chance of code reuse is greater.

 

2. After a DLL is modified, it can only be deleted and re-registered in MTS, because after each re-compilation, the ID value of the object in the registry will be re-generated.

 

3. when you call class methods and functions with parameters from ASP, all variable parameters must be converted using the corresponding type conversion function before being passed in. Otherwise, the Type Mismatch Error may occur, because VBScript only has the Variant type, it cannot be automatically converted to another type. For example, there are the following function definitions:

 

Public Function Fun1 (p1 as string, p2 as integer) as integer
End Function
In the ASP program, it should be called as follows:
<%
P1 = obj. property1 "Property1 is a string property
P2 = obj. property2 "Property2 is an integer property
A = obj. Fun1 (cstr (p1), cint (p2 ))
A = obj. Fun1 ("aaa", 10) "constant parameter need not be changed
%>

 

The following two statements are incorrect:

 

<%
P1 = obj. property1 "Property1 is a string property
P2 = obj. property2 "Property2 is an integer property
A = obj. Fun1 (p1, p2) "incorrect, p1 and p2 are variant variables
P1 = cstr (p1)
P2 = cint (p2)
A = obj. Fun1 (p1, p2) "still incorrect
%>
Here, the second method is still incorrect. Even after type conversion, p1 and p2 are still Variant variables. In VBScript, data types and type conversion functions only play a role in expression operations, and variables only have Variant.

 

Conclusion
I have discussed the theory and practice of multi-layer structure and hope it will be helpful for your development. There is another question, that is, how to design the Class and Class Members. This involves both the object-oriented programming theory and some practical experience. Please refer to the relevant OOP theory books and continue to summarize them in practice. I believe you will be able to design your own perfect multi-layer structure applications.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.