Asp深度揭密(下)

來源:互聯網
上載者:User
四、Asp組件的開發與使用:

1. 組件的特點?

l 優點:
n 調用方便,節省代碼
n 安全性高
n 支援交易處理,多組件聯合
n 運行速度快
n 升級、修改組件不需修改頁面,因此擴充性好
l 缺點:
n 開發及調試困難

2. 如何使用VB開發?

⑴.開啟VB>>New Project>>ActiveX DLL

⑵.修改項目名稱為course

⑶.修改類別模組的名字為conn_db

⑷.Project>> References,引用COM  Service Type Library和Microsoft Active Server Pages Object Library。

⑸.修改類代碼如下:

'建立資料庫連接並輸出資料庫欄位
Dim Response As Response
Dim Request As Request
Dim Server As Server
Dim Application As Application
Dim Session As Session

Private Sub Class_Initialize()
Dim objContext As ObjectContext
Set objContext = GetObjectContext()
Set Response = objContext("Response")
Set Request = objContext("Request")
Set Server = objContext("Server")
Set Application = objContext("Application")
Set Session = objContext("Session")
End Sub

Sub conn_db()
Set conn = CreateObject("adodb.connection")
conn.open "course_dsn", "course_user", "course_password"
Set rs = CreateObject("adodb.recordset")
rs.open "select * from user_info", conn, 1, 1

If rs.recordcount > 0 Then
For i = 1 To rs.recordcount
Response.write "<br>" & rs("user_name") & "<br>"
If rs.EOF Then Exit For
rs.movenext
Next
End If
rs.Close
Set rs = Nothing
conn.Close
Set conn = Nothing
End Sub

⑹.添加一新類cutstr

⑺.修改類代碼如下:

'截取字串
Function cutstr(str, length)
If Len(str) > length Then
cutstr = Left(str, length) & "..."
Else
cutstr = str
End If
End Function

⑻.File>>Save

⑼.File>>make course.dll

3. 註冊組件:MTS和regsvr32.exe

有兩種方式註冊組件:MTS和使用regsvr32.exe。MTS是值得推薦的,因為它具有下列優點:
n 動態卸載平衡,提高組件和基於組件的應用程式的升級性。
n 包含公布和提交事件和隊列組件的能力,使得更容易與多個組件聯合。

要想使組件具有MTS的特性,必須對組件做少許改動。在NT和98下開發時,必須在項目中引用Microsoft Transaction Server Type Library,在Windows 2000下開發,必須引用COM  Service Type Library。

⑴.regsvr32註冊:

regsvr32.exe是system32下面的一個可執行檔,它將組件資訊讀入註冊表,以便Asp調用。
使用命令列進入組件dll檔案所在的目錄,執行“regsvr32 dll_file_name”即可。

運行regedit,在HKEY_CLASSES_ROOT下就會找到course.conn_db項和course.cutstr項,表明組件註冊成功。

⑵.使用MTS註冊:

①.開始>>程式>>管理工具>>元件服務

②.展開目錄至如下狀態:

③.按照嚮導,下一步,直到如下對話方塊,點擊“建立一個空的應用程式”:

④.在接下來的對話方塊中,為應用程式起名為“course”,其他預設,直至完成

⑤.展開course應用程式,右鍵,建立一個組件

⑥.按照提示,繼續,出現如下對話方塊時,選擇“匯入已被註冊的組件”

⑦.選擇我們開發的組件,下一步,直至完成

⑧.這時候,可以發現course應用程式下已經多了兩個組件:

4. 在Asp中調用組件

asp_use_com.asp
<%
'asp調用com組件
set cutstr_obj=server.createobject("course.cutstr")
response.write cutstr_obj.cutstr("abcdefghijk",3)&"<br>"
set cutstr_obj=nothing

set conn_obj=server.createobject("course.conn_db")
conn_obj.conn_db()
set conn_obj=nothing
%>

效果:
abc...

ahyi

tuth

說明調用成功。

5. 卸載組件

⑴.使用regsvr32註冊的組件,使用-u開關卸載:

注意:先進入組件dll所在的目錄,然後使用“regsvr32 –u dll_file_name”卸載;卸載後重啟IIS即可。

⑵.使用MTS註冊的組件,先在“元件服務”中刪除對應的應用程式,然後再執行步驟 ⑴ 以徹底卸載組件。

6. Dll組件存放位置和許可權設定

⑴.我們只需要把編譯產生的Dll檔案拷貝出來即可,其他的檔案不用做處理
⑵.要把Dll放到Web網站之外,如system32目錄裡,防止被下載
⑶.Dll的檔案權設定為System讀取,Internet使用者遍曆檔案夾/運行檔案
⑷.Dll在IIS中去掉所有的許可權,如讀取,指令碼自願訪問等
經過上述處理,可以確保Dll檔案的安全。

7. 其他

如何在組件中使用Asp的對象以方便的將Asp代碼移植為COM組件?

五、IIS最佳化配置

1.Web網站選項卡:IP、連接埠、虛擬機器主機、串連、日誌
2.ISAPI篩選器:加入PHP和JSP支援
3.主目錄配置選項卡:I IS許可權設定(結合檔案權)、執行許可、應用程式保護、映射、緩衝、父路徑、出錯資訊
4.其他選項卡:自訂錯誤、Http頭、目錄安全性、文檔
5.檔案壓縮帶來的好處和壞處

六、其他

1. 發送郵件(JMail;Ms smtp)

使用Microsoft Smtp寄送電子郵件
⑴.安裝Microsoft SMTP Service
⑵.設定Microsoft SMTP Service
⑶.代碼部分:
mail_smtp.asp
<%
sub sendmail(fromwho,towho,subject,body)
dim mymail
set mymail = server.createobject("cdonts.newmail")
mymail.from = fromwho
mymail.to = towho
mymail.subject = subject
mymail.body = body
mymail.send
set mymail = nothing
end sub
%>

該子程式接受4個與下列各條對應的參數。
l 郵件寄件者的email地址
l 郵件接收者的email地址
l 郵件主題
l 郵件內容

使用方法:
<%
fromWho=…
toWho=…
Subject=…
Body=…

IF toWho <> "" THEN
sendMail fromWho, toWho, Subject, Body
END IF
%>

使用Jmail發送Email
略,有興趣可以和我探討,Jmail這個軟體我也有。

2. 解壓Zip檔案(Wscript.Shell和Winzip command line;Java組件)

⑴.安裝Winzip 8.1以上
⑵.安裝Winzip command line
⑶.將工作目錄的檔案權設定為Internet使用者可以讀取、寫入和修改
⑷.代碼部分:
unzip_a_zipfile.asp
<%
'用shell對象啟動程式
'zip_path是具體zip檔案的路徑,如c:\test.zip
'path是存放解壓後檔案的路徑
'ond是命令列參數
set wshshell = server.createobject("wscript.shell")
issuccess = wshshell.run ("wzunzip -ond "&zip_path&" "&path,1,true)

'刪除zip檔案
set myfileobject=server.createobject("scripting.filesystemobject")
myfileobject.deletefile zip_path

'判斷是否成功以繼續操作
if issuccess = 0 then 
'成功
...
else
'失敗
...
end if
%>

3. 操作XML檔案

本次交流時間有限,有時間再做詳細探討

4.檔案上傳

⑴.安裝檔案上傳組件Asp fileup(支援多檔案上傳,檔案類型及大小判斷,檔案上傳後改名等)
⑵.重起IIS以使上傳組件生效
⑶.設定上傳目錄的檔案權為Internet使用者可以讀取、寫入和修改
⑷.代碼部分
upload_file.htm
<style type="text/css">
<!--
.input {background-color: #FFFFFF; border-bottom: black 1px solid;border-left: black 1px solid; border-right: black 1px solid;border-top: black 1px solid; color: #000000;font-family: Georgia; font-size: 9pt;color: midnightblue;}
a:link {color: #1B629C; text-decoration: none}
a:hover {color: #FF6600; text-decoration: underline}
a:visited {text-decoration: none}
-->
</style>

<center>
<form enctype="multipart/form-data" method="post" action="upload_file.asp" name="Upload">
<input type="hidden" name="CopyrightInfo" value="http://www.chinaasp.com";>
請選擇檔案:<input type="file" name="file1" class="input"><br><br>
請選擇檔案:<input type="file" name="file2" class="input"><br><br>
</form>
<br><br>
<a href="javascript:document.Upload.submit();"> 提 交 </a>
</center>

upload_file.asp
<%
on error resume next

'定義獲得檔案尾碼的函數
function getfileextname(filename)
pos=instrrev(filename,".")
if pos>0 then 
getfileextname=mid(filename,pos 1)
else
getfileextname=""
end if
end function

'定義擷取檔案正名的函數
function getfilename(filename)
lens=len(filename)-len(getfileextname(filename))-1
getfilename=left(filename,lens)
end function

'建立檔案上傳組件的對象
set fileup=server.createobject("chinaasp.upload")

'迴圈讀取使用者上傳的檔案,並儲存在伺服器上
for each f in fileup.files

'當使用者沒有選擇檔案或檔案大小超過10m時返回到選擇上傳檔案的頁面
if f.filename="" or f.filesize>10485500 then response.redirect "upload_file.htm"

'擷取儲存的路徑
path=server.mappath("upload_file.asp")
path=left(path,len(path)-15)

'儲存檔案
f.saveas path&getfilename(f.filename)&"."&getfileextname(f.filename)

next

response.redirect "upload_file.htm"
%>

5.磁碟機/目錄/檔案操作

本次交流時間有限,有時間再做詳細探討

6. Asp編寫與調試經驗:cookies和session如何選擇、cookies數量陷阱、頁面到期和緩衝設定、移植性如何保證、如何應付內部伺服器500錯誤……

1.Cookies和Session的選擇:
⑴.共同特點
⑵.不同之處:
①.工作方式
②.到期條件
③.對伺服器的效能影響

2.Cookies數量陷阱:
IIS可以儲存一般的cookies不超過20個,再定義新的Cookies以前的Cookies的值就丟失了,這樣對大型應用顯然局限性非常大,如何解決這個問題呢?
答案是使用二維Cookies。

例子:

測試一維Cookies數量極限:
test_cookies_1.asp
<%
for i=1 to 50
response.cookies("cookies_"&i)=i
next
%>

test_cookies_2.asp
<%
for i=1 to 50
response.write request.cookies("cookies_"&i)&"<br>"
next
%>

效果:
先訪問test_cookies_1.asp,再訪問test_cookies_2.asp,,發現了什嗎?

test_cookies_3.asp
<%
for i=1 to 50
response.cookies("cookies_"&i)=i
next

for i=1 to 50
response.write request.cookies("cookies_"&i)&"<br>"
next
%>

效果:
沒有Cookies丟失!!!!

測試二維Cookies數量極限:
test_cookies_4.asp
<%
for i=1 to 301
response.cookies("tuht")("cookies_"&i)=i
next
%>

test_cookies_5.asp
<%
for i=1 to 301
response.write request.cookies("tuht")("cookies_"&i)&"<br>"
next
%>

效果:
使用這種方式可以使用201*20=4020個Cookies!!!!

3.頁面到期和緩衝設定
<%
'到期和緩衝處理
response.buffer=true
response.cachecontrol="no-chache"
response.expiresabsolute=now()-1
response.expires=0
%>
html中還可以做設定:
<meta content="no-cache" http-equiv="Pragma">
<meta HTTP-EQUIV="Expires" CONTENT="0">

4.移植性的保證
⑴.包含檔案
<!--#include file="top.asp" -->
⑵.使用server.mappath尋找檔案路徑,避免在頁面中直接使用絕對路徑
⑶.盡量使用組件封裝商務邏輯

5.調試內部伺服器500的錯誤
⑴.設定IIS顯示具體的錯誤資訊
⑵.分步調試,由上而下
⑶.列印某些重要的變數的值,檢查是否為我們預期
⑷.根據經驗來判斷錯誤

7. 操作Word文檔

⑴.安裝Office 2000,其中Word 2000必選
⑵.設定IE中Internet的安全性:ActiveX控制項和外掛程式全部啟用
⑶.設定工作目錄的檔案權為Internet及System讀取/修改/寫入
⑷.編寫模版course.dot
⑸.具體代碼:
opr_doc_inc.asp
<%
Response.write "Dim Var_Num" & chr(13)
Response.write " Var_Num = 2 " & chr(13)
Response.write "Dim varstrings(2)" & chr(13)
Response.write "varstrings(0)=" & chr(34) & "起草人:" & chr(34) & chr(13)
Response.write "varstrings(1)=" & chr(34) & "日期:" & chr(34) & chr(13)
Response.write "Dim varvalues(2)" & chr(13)
Response.write "varvalues(0)=" & chr(34) &"起草人:塗海濤"& chr(34) & chr(13)
Response.write "varvalues(1)=" & chr(34) & "日期:"&date()& chr(34) & chr(13)
%>

Sub instead(word)
Set myRange = word.ActiveDocument.Content
for i=0 to Var_Num - 1 
call myRange.Find.Execute(varStrings(i),false,false,false,false,false,false,false,false,varvalues(i),2)
Next
End Sub

opr_doc.asp
<%
'擷取儲存的路徑
path=server.mappath("opr_doc.asp")
path=left(path,len(path)-11)
filenames=path&"test.doc"

w1="word.activedocument.saveAs"&chr(32)&chr(34)&filenames&chr(34)
w2="wApp.Documents.open"&chr(32)&chr(34)&filenames&chr(34)
%>
<script language="vbscript">
On Error Resume Next
'產生指定檔案名稱的Word文檔
Dim word
set word = CreateObject("Word.Application")
if Err.number > 0 Then
Alert "發生錯誤,請確認檔案是否存在"
else
word.visible = False
word.documents.open "<%response.write path%>course.dot"
<%Response.write w1%>
word.documents.close
set word=nothing
end if

<!--#include file="opr_doc_inc.asp"-->

Dim wApp
Set wApp = CreateObject("Word.Application")
If Err.number > 0 Then
Alert "發生錯誤,請確認檔案是否正確建立"
else
wApp.visible = True
<%Response.write w2%>
call instead(wApp)
set wApp=nothing
end if
</script>

效果:看看產生了doc檔案嗎?這個建立的doc檔案和模版檔案有什麼區別?起草人和日期發生了變化了嗎?儲存一下,看看新產生的doc檔案的內容。

附:
1.以上全部代碼在Windows 2000 Server SP2 IIS 5.0 MS SQL Server 2000 Office 2000下測試通過
2.設定資料庫:資料庫名course,使用者course_user,密碼course_password,ODBC驅動為course_dsn,連接埠為2433,描述表結構的指令碼在共用目錄下。
3.Asp fileup、Jmail、Winzip 8.1、Winzip command line這幾個軟體請自行下載。
4.資料庫指令碼檔案:
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[output_1]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[output_1]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[return_1]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[return_1]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[user_info_1]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[user_info_1]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[user_info_2]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[user_info_2]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[user_info_3]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[user_info_3]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[user_info]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[user_info]
GO

CREATE TABLE [dbo].[user_info] (
[id] [int] IDENTITY (1, 1) NOT NULL ,
[user_name] [varchar] (40) COLLATE Chinese_PRC_CI_AS NOT NULL ,
[password] [varchar] (20) COLLATE Chinese_PRC_CI_AS NOT NULL 
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[user_info] WITH NOCHECK ADD 
CONSTRAINT [PK_user_info] PRIMARY KEY CLUSTERED 
(
[user_name]
) ON [PRIMARY] 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE [output_1]
@sid int output
AS
set @sid=2
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE [return_1]
(@user_name varchar(40),@password varchar(20))
AS
if exists(select id from user_info where user_name=@user_name and password=@password)
return 1
else
return 0
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE [user_info_1]
(@user_name varchar(40),@password varchar(20))
AS
select id from user_info where user_name=@user_name and password=@password
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE [user_info_2]
(@user_name varchar(40),@password varchar(20))
AS
SET XACT_ABORT ON
BEGIN TRANSACTION
delete from user_info where user_name=@user_name and password=@password
COMMIT TRANSACTION
SET XACT_ABORT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE [user_info_3] AS
select * from user_info
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.