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<