能否在VBScript中创建类Request对象的自定义集合对象?
在VBScript中实现类Request.QueryString的自定义对象
完全可以实现这种双重行为,并非Request对象独有,通过VBScript的类(Class)就能模拟这个特性。核心是利用默认可选参数属性处理直接输出和索引访问,同时通过枚举器支持For Each遍历,内部用字典存储键值对并实现 sanitize 逻辑。
实现代码示例
Class SafeQueryString Private m_colData ' 内部存储键值对的字典 ' 类初始化:创建字典,设置不区分大小写(和Request.QueryString一致) Private Sub Class_Initialize() Set m_colData = CreateObject("Scripting.Dictionary") m_colData.CompareMode = vbTextCompare End Sub ' 类销毁:释放字典资源 Private Sub Class_Terminate() Set m_colData = Nothing End Sub ' 默认属性:支持无参数返回拼接字符串,带参数返回对应值 Default Property Get Item(Optional Key) If IsEmpty(Key) Then ' 返回 sanitize 后的拼接字符串 Item = BuildSanitizedQueryString() Else ' 返回对应键的 sanitize 后的值 Item = SanitizeValue(m_colData(Key)) End If End Property ' 支持For Each遍历的枚举器 Public Property Get _NewEnum() Set _NewEnum = m_colData._NewEnum End Property ' 添加键值对(支持重复键,模拟Request的多值处理) Public Sub Add(Key, Value) Dim sanitizedKey, sanitizedValue sanitizedKey = SanitizeKey(Key) sanitizedValue = SanitizeValue(Value) If m_colData.Exists(sanitizedKey) Then ' 重复键用逗号分隔,和Request.QueryString行为一致 m_colData(sanitizedKey) = m_colData(sanitizedKey) & "," & sanitizedValue Else m_colData(sanitizedKey) = sanitizedValue End If End Sub ' 自定义sanitize键的逻辑(根据需求调整) Private Function SanitizeKey(Key) ' 示例:移除非法字符,避免注入风险 SanitizeKey = Replace(Replace(Key, "<", ""), ">", "") End Function ' 自定义sanitize值的逻辑(根据需求调整) Private Function SanitizeValue(Value) ' 示例:移除HTML标签,同时做URL编码 Value = Replace(Replace(Value, "<", ""), ">", "") SanitizeValue = Server.URLEncode(Value) End Function ' 构建 sanitize 后的查询字符串 Private Function BuildSanitizedQueryString() Dim arrKeys, i, key, value, parts arrKeys = m_colData.Keys If UBound(arrKeys) = -1 Then BuildSanitizedQueryString = "" Exit Function End If ReDim parts(UBound(arrKeys)) For i = 0 To UBound(arrKeys) key = arrKeys(i) value = m_colData(key) parts(i) = SanitizeKey(key) & "=" & value ' 值已经在Add时做过sanitize和编码 Next BuildSanitizedQueryString = Join(parts, "&") End Function End Class
使用示例
' 初始化自定义对象并添加数据 Set safeQs = New SafeQueryString safeQs.Add "var1", "valone<script>" safeQs.Add "var2", "valtwo>" safeQs.Add "var1", "valthree" ' 重复键 ' 1. 遍历键 Response.Write "遍历键:<br>" For Each key In safeQs Response.Write key & ": " & safeQs(key) & "<br>" Next ' 2. 直接输出拼接后的字符串 Response.Write "<br>直接输出:<br>" Response.Write "mysite.com?" & safeQs ' 3. 索引访问单个值 Response.Write "<br>单个值:<br>" Response.Write safeQs("var1")
关键特性说明
- 默认可选参数属性:
Item属性支持无参数调用(直接输出对象时触发),返回 sanitize 后的拼接字符串;带参数时返回对应键的 sanitize 值。 - For Each遍历:通过
_NewEnum属性返回字典的枚举器,实现和Request.QueryString一致的遍历行为。 - Sanitize逻辑:自定义
SanitizeKey和SanitizeValue方法,可根据需求调整过滤规则(比如XSS防护、URL编码等)。
内容的提问来源于stack exchange,提问作者user1693404
相关产品推荐
相关产品推荐

