server 1 問題提出
經常看到一些網站或者Web應用系統,在瀏覽器看來,他們只採用一個頁面,所有的頁面地址都是通過這個頁面的參數連結得到的。例如:
http://abc.com/default.asp?pg=AdminPage&command=View
http://abc.com/default.asp?pg=ShowPage&command=List
等等諸如此類的東西。以前我沒有仔細想過該怎麼實現,也許頁面差別不大用幾個不同的Sub來做就行了;可是仔細看了看兩個地址,兩個頁面的差別太大了;如果這一個頁麵包含這麼多的Sub,這對程式員而言簡直是一種摧殘,而且美工根本無法插手。我和一個網友討論了很久,他提出用ISAPI,我覺得很恐怖。
後來想了想,記起來轉向的幾種方法:Server.Transfer, Response.Redirect, Server.Execute就不算了。Response.Redirect是IIS明確表明不太用的(但是我以前做ASP的時候用得最多)。後來看看Server.Transfer,越看越覺得能夠使用的樣子。IIS的協助中進行了如下闡述:
When you call Server.Transfer, the state information for all the built-in objects will be included in the transfer. This means that any variables or objects that have been assigned a value in session or application scope will be maintained. In addition, all of the current contents for the request collections will be available to the .asp file receiving the transfer. 也就是說,所有的Request集合、Session、Application都是共用的。這樣就能夠在不同的頁面進行互動了。
看到這些,我就動手做了一些代碼,闡述如下:
2 實現
我的初步想法是:在一個xml檔案中記錄所有的名稱-地址對照集合,然後在default.asp中讀取這個集合,在查詢字串的pg中讀取page name, 然後Server.Transfer到相應的頁面中。關鍵代碼如下:
default.asp:
<!--#include file="Functions.asp"-->
<%
On Error Resume Next
Response.CharSet = "gb2312"
Dim opageName, opageURL
opageName = Request.QueryString("pg")
If opageName <> "" Then
opageURL = GetPage(opageName)
Else
Response.Write "OKOK, You didn't pass a pg parameter."
Response.End
End If
If opageURL = "" Then
Response.Write "找不到對應檔for: " & opageName
Else
Server.Transfer(opageURL)
End If
If Err.Number <> 0 Then
Response.Write Err.Description
End If
%>
Functions.asp:
<%
Option Explicit
Dim configPath, Page_URL_Dict
configPath = Server.MapPath("./conf/app-conf.xml")
Set Page_URL_Dict = Server.CreateObject("Scripting.Dictionary")
‘根據pageName取得頁面地址
Function GetPage(pageName)
If Page_URL_Dict.Count = 0 Then
ReadPageURLToDict
End If
GetPage = Page_URL_Dict(pageName)
End Function
‘初始化pageName-pageURL對照字典
Function ReadPageURLToDict()
On Error Resume Next
Page_URL_Dict.RemoveAll
Dim logNode, xmlDom, root
Set xmlDom = Server.CreateObject("Microsoft.XMLDOM")
xmlDom.async = False
xmlDom.load(configPath)
Set root = xmldom.selectSingleNode("//url-mappings")
For Each logNode In root.childNodes
Page_URL_Dict.Add logNode.childNodes(0).text, logNode.childNodes(1).text
Next
Set xmlDom = Nothing
If Err.Number <> 0 Then
Response.Write Err.Source & "<br>"
Response.Write Err.Description & "<br>"
End If
End Function
%>
app-conf.xml
<?xml version="1.0"?>
<app-conf>
<url-mappings>
<url-mapping>
<page-name>pgHome</page-name>
<page-url>Page2.asp</page-url>
</url-mapping>
<url-mapping>
<page-name>pgShowNews</page-name>
<page-url>shownews-1_0.asp</page-url>
</url-mapping>
<url-mapping>
<page-name>pgHtml</pag