目录
- Server 对象简介
- Server.CreateObject 方法
- Server.HTMLEncode 和 Server.URLEncode 方法
- Server.MapPath 方法
- Server.GetLastError 方法
- Server.ScriptTimeout 属性
- 完整示例代码
- 参考资料
- 出站链接
1. Server 对象简介
Server
对象是 ASP 提供的一个内置对象,主要用于执行服务器端操作,如创建 COM 组件、获取服务器错误、处理超时等。
📌 常见用途:
- 创建 COM 组件
- 编码 HTML 和 URL
- 获取文件的 物理路径
- 处理 脚本超时
- 获取 服务器错误信息
2. Server.CreateObject 方法
📌 Server.CreateObject("ProgID")
用于创建 COM 组件的实例,例如 Scripting.FileSystemObject
、CDOSYS
邮件对象等。
示例:创建 FileSystemObject 读取文件
<%
Dim objFSO, objFile
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(Server.MapPath("data.txt"), 1)
Response.Write objFile.ReadAll
objFile.Close
Set objFile = Nothing
Set objFSO = Nothing
%>
📌 常见 COM 组件:
组件名称 | ProgID | 作用 |
---|---|---|
FileSystemObject | Scripting.FileSystemObject | 文件操作 |
CDOSYS | CDO.Message | 发送邮件 |
ADODB.Connection | ADODB.Connection | 访问数据库 |
3. Server.HTMLEncode 和 Server.URLEncode 方法
📌 HTMLEncode 和 URLEncode 用于编码字符串,防止 XSS 攻击或 URL 乱码。
示例:防止 HTML 注入攻击
<%
Dim unsafeText
unsafeText = "<script>alert('XSS');</script>"
Response.Write Server.HTMLEncode(unsafeText)
' 输出:<script>alert('XSS');</script>
%>
示例:URL 编码
<%
Dim queryString
queryString = "name=张三&city=北京"
Response.Write Server.URLEncode(queryString)
' 输出:name%3D%E5%BC%A0%E4%B8%89%26city%3D%E5%8C%97%E4%BA%AC
%>
4. Server.MapPath 方法
📌 Server.MapPath("虚拟路径")
用于获取 服务器上的物理路径。
示例:获取文件的真实路径
<%
Response.Write Server.MapPath("/uploads/image.jpg")
' 输出:C:\inetpub\wwwroot\uploads\image.jpg
%>
📌 应用场景:
- 上传文件时获取存储路径
- 读取或写入服务器文件
5. Server.GetLastError 方法
📌 Server.GetLastError()
返回 上一次 ASP 运行时错误,用于调试错误信息。
示例:捕获 ASP 运行时错误
<%
On Error Resume Next
Dim objFile
Set objFile = Server.CreateObject("Scripting.FileSystemObject")
Set objFile = objFile.OpenTextFile("nonexistent.txt", 1)
If Err.Number <> 0 Then
Dim objError
Set objError = Server.GetLastError()
Response.Write "错误代码:" & objError.Number & "<br>"
Response.Write "错误描述:" & objError.Description
End If
%>
📌 常见错误处理:
- 记录到日志
- 返回友好的错误页面
6. Server.ScriptTimeout 属性
📌 Server.ScriptTimeout
控制 ASP 脚本的 超时时间(默认 90 秒)。
示例:增加脚本超时时间
<%
Server.ScriptTimeout = 180 ' 允许脚本运行 180 秒
%>
📌 应用场景:
- 处理 大数据计算
- 长时间数据库查询
7. 完整示例代码
<%
' 设置脚本超时
Server.ScriptTimeout = 120
' 创建 FileSystemObject 读取文件
Dim objFSO, objFile
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(Server.MapPath("data.txt"), 1)
' 读取文件内容
Response.Write "<h2>文件内容:</h2>"
Response.Write Server.HTMLEncode(objFile.ReadAll)
' 关闭对象
objFile.Close
Set objFile = Nothing
Set objFSO = Nothing
' 显示服务器信息
Response.Write "<h2>服务器信息:</h2>"
Response.Write "文件路径:" & Server.MapPath("/uploads/image.jpg") & "<br>"
Response.Write "Session ID:" & Session.SessionID & "<br>"
%>
8. 参考资料
- Microsoft Docs – ASP Server 对象
- W3Schools – ASP Server Methods
- IIS 官方文档 – ASP 编程指南
9. 出站链接
掌握 ASP Server 对象,你就能更好地处理服务器端逻辑,如 创建 COM 组件、文件操作、错误管理和路径解析,提高 ASP 开发效率!🚀
发表回复