Giới thiệu tổng quan về lập trình ASp

14 697 3
Giới thiệu tổng quan về lập trình ASp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Giới thiệu tổng quan về lập trình ASp

1. Đặc điểm:Tên file: .asp Phải cài thêm Microsoft Active Server Page để bổ trợ cho Web Server, chuyên xử lý các script viết trong file .asp. Cho phép viết ứng dụng theo kiểu Server Side => các trang web sẽ sẽ đợc xử lý tại Server trớc khi gửi xuống Client. Các mã lệnh đợc chèn vào trong khắp trang web và đợc xử lý tuần tự. Mã lệnh là các Script, hiện ASP cho phép dùng 2 srcript là VBScript hoặc JavaScript. Lựa chọn Script đợc đặt ngay tại dòng đầu file:<%@LANGUAGE = VBSCRIPT%><%@LANGUAGE = JSCRIPT%>Ngầm định là VBScript. Các đoạn mã không phân biệt dài ngắn đợc đặt trong dấu hiệu: <% %> Các biến không cần khai báo mà tự khi gán giá trị cho nó sẽ xác định biến. Để in ra các biến trong trang web sử dụng nh mã sau:<% =s %> Để làm việc với hệ thống file, thao tác với Database . => cần phải sử dụng các đối tợng kiểu Active X của ASP hay cài đặt thêm vào. Để lấy các giá trị truyền từ client lên dùng phơng thức request.Ex: s = request(Company)=> Lấy giá trị của biến Company.2. Sử dụng các đối t ợng: ASP cho phép sử dụng các đối tợng kiểu Active X. Để khai báo ta dùng phơng thức CreateObject của đối tợng Server có sẵn.Ex: Set f = Server.CreateObject(Scripting.FileSystemObject);Tổng quan: Set param = Server.CreateObject(PacketName.ClassName) ProgIDSau đó có thể sử dụng các hàm của đối tợng đó.Để giải phóng dùng Set f = nothing3. Truy nhập hệ thống file:<%Dim objFileDim objStreamSet objFile = Server.CreateObject(Scripting.FileSystemObject);Set objStream = objFile.OpenTextFile(Server.Mapath(/ASP) &_ \Chapter05\Listing 5-9\tips.txt)Randomize TimerIntLine = Int(Rnd*19)1 For i=0 to intLineObjStream.SkipLineNextStrTxt = objStream.ReadLineObjStream.CloseSet objFile= NothingSet objStream= Nothing%>=> Để tạo file mới dùng phơng thức CrateTextFile của objFile.Để ghi một dòng văn bản dùng objStream.WriteLine s.4. Truy nhập cơ sở dữ liệu:<%Dim objConnectionSet objConnection = Server.CreateObject(ADODB.Connection)ObjConnection.Open Publication, sa, Dim objRecordSetSet objRecordSet = Server.CreateObject(ADODB.RecordSet)ObjRecordSet.Open Select pub_name From Publishers, objConnection%> Đối tợng kiểu Connection: tạo kết nối ADO tới Database. Đối tợng kiểu RecordSet: cho phép thao tác trên table (select,update .) của Connection đã thiết lập.<% Do While Not objRecordSet.EOF %><% = objRecordSet(pub_name)%><% objRecordSet.MoveNextLoopObjRecordSet.closeObjConnection.closeSet objRecordSet = nothingSet objConnection = nothing %> Chú ý: khi thêm, cập nhật dữ liệu ngoài việc dùng SQL, có thể thêm theo cách : With objRecordSet do.AddNew .Field(Authors) = Homes. Field(Title) = Iliad.UpdateEnd With Có thể kết nối trực tiếp không qua DSN của ODBC nh sau :2 <% Set objConnection = Server.CreateObject(ADODB.Connection)StrCnn = driver = {SQL Server}; Server = smas; uid = sa; pwd= ; database= pubsobjConnection.Open strCnn%>5. Phân trang RecordSetKhi select => cho kết quả 1 bảng gồm nhiều hàng. Tuy nhiên mỗi lần chỉ muốn sử dụng một vài hàng, ví dụ: bảng 50 hàng, mỗi lần hiển thị 10 hàng => sử dụng kỹ thuật paging. ADO cung cấp các thuộc tính của Recordset nh: PageSize, PageCount, AbsolutePage.PageCount: số trang, PageSize: số hàng.ở đây ta dùng biến session CurrentPage để ghi nhận trang hiện hành.<% Select Case Request.QueryString(Direction)Case NullSession(CurrentPage) = 1 Case NextSession(CurrentPage) = Session(CurrentPage) + 1Case PreviousSession(CurrentPage) = Session(CurrentPage) - 1End Select %> Chú ý: Request.QueryString(Direction) <=> QueryString(Direction)Tiến hành kết nối truy vấn dữ liệu.<%const adOpenKeySet = 1dim objConnection không cần khai báo cũng đợcdim objRexordsetSet objConnection = Server.CreateObject(ADODB.Connection)Set ObjConnection.Open Biblio, , Dim strSQLStrSQL = Select * from Authors Set objRecordSet = Server.CreateObject(ADODB.RecordSet)ObjRecordSet.PageSize = 10ObjRecordSet.Open strSQL, objConnection, adOpenKeysetObjRecordSet.AbsolutePage = CLng(Session(CurrentPage))%><P> Page = <%=Session(CurrentPage) %> of <%=ObjRecordSet.PageCount><% Dim iFor i = 1 to ObjRecordSet.PageSize %><% = ObjRecordSet(Authors) %> .3 <% ObjRecordSet.MoveNextNext %><% if CLng(Session(CurrentPage)) < ObjRecordSet.PageCount Then %><P> <A HREF = paging.asp?Direction=Next>Next Page</A></P><%Enf if%><% If CLng(Session(CurrentPage)) > 1 then %><P><A Href = paging.asp?Direction=Previous>Previous Page</A></P><%Enf if%><% ObjRecordSet.closeObjConnection.closeSet objRecordSet = nothingSet objConnection = nothing %>6. Đối t ợng Application: Đối tợng này cho phép tạo các biến ứng dụng. Đó là các biến cho tất cả các user của một ứng dụng web. Tất cả các user mà yêu cầu các trang web từ một th mục web có thể chia xẻ với nhau các biến định nghĩa trong các trang đó.<% Application.LockApplication(Company) = VASCApplication.Unlock %>ở đây định nghĩa 1 biến là Company, có giá trị là VASC. Vì rằng biến có thể bị tranh chấp nên phải đặt giữa Lock và Unlock.<% Application.LockApplication(Time) = NowApplication.Unlock %>7. Đối t ợng Session: Cho phép tạo ra các biến ứng với từng ngời dùng. Chẳng hạn biến có tên là UserName, ứng với mỗi user có một giá trị cụ thể khác nhau, phân biệt. Nhng khi sử dụng thì tổng quát cho các user. Thực ra mỗi biến sẽ đợc server phát sinh và gán cho nó một giá trị định danh GUID (Globally Unique Identifier, 128 bit) và gửi tới Browser. Browser sẽ lu trữ GUID đó và sử dụng để yêu cầu dữ liệu từ biến có GUID tơng ứng trên Server.<% Session(Company) = NewTechSession(Email) = leha@hotmail.com %>My Company : <% Session(Company) %>Email : <% Session(Email) %>Các biến Session này sẽ bị huỷ bỏ sau một khoảng thời gian (khoảng 20) ngời dùng thôi truy xuất các trang web trong th mục web. Chú ý là trong file global.asa => cho pháp đặt các biến, code vào các thủ tục Session_OuStart và Session OuEnd. Ví dụ:<SCRIPT LANGUAGE = VBScript RUNAT = Server>Sub Session_OuStartSession(Company) = VASC4 Session(Email) = thanhha@vasc.vnn.vnEnd sub</SCRIPT>8. Đối t ợng Request: Để gửi dữ liệu lên Server, ta sử dụng Form trong trang Web. Tên của các đồi tợng web nh Text, Button nằm trong form sẽ đợc dùng nh tên biến khi phân tích, lấy dữ liệu trên Server. Trong form có button kiểu Submit để ngời dùng đẩy dữ liệu lên Server.Form có hai thuộc tính là Action và Method. Action quy định file (.asp) mà sẽ đón nhận và xử lý dữ liệu đẩy lên. method quy định cách thức gửi dữ liệu; nếu là POST thì tất cả dữ liệu trong form sẽ đóng gói và đẩy lên Server; Nếu là GET thì dữ liệu đợc gửi đi nh một phần của URL, thờng là sau dấu ?.<Form Method = POST Action = http://www.vnn.vn/data.asp> Kiểu gửi dữ liệu GET cũng có thể lợi dụng để gửi đi dới dạng một link.< A href = http://www.vnn.vn/data.asp?name=ha&company=VASC >Test</a> Gửi theo GET thì độ lớn bị hạn chế và không che dấu dữ liệu.Để lấy dữ liệu ta dùng phơng thức của đối tợng Request.S = Request.Form(Name)<=> S = Request(Name)Trong trờng hợp dữ liệu đợc đa lên từ 1 hyperlink, có thể dùng:S = Request.QueryString(Name)<=> S = Request(Name) Đối tợng Request cũng cho phép lấy giá trị các biến môi trờng nh LOGON_USER, HTTP_USER_AGENT, ví dụ:Request.ServerVariables(LOGON_USER)Request.ServerVariables(HTTP_USER_AGENT)9. Đối t ợng Reponse: Đối tợng này quản lý tất cả dữ liệu, nội dung sẽ đợc gởi cho Browser từ ASP.<% = Company%><=> <% Reponse.Write Company %>Reponse cung cấp 1 thuộc tính là Expires, quy định thời gian (phút) mà trang Web chứa trong cache của IE. Vậy, nếu đặt dòng <% Response.Epires = 0 %> thì trang Web sẽ không chứa trong cache của IE.10. Đối t ợng Server: Đối tợng Server cung cấp hàm CreateObject, để tạo ra các đối tợng (instance) của Active X. Tham số truyền vào là ProgID (Program Identifier) của Component cần tạo instance.Set MyObject = Server.CreateObject(Mail.Connector)Đoạn mã sau in ra các biến Server :5 < % For each name in Request.ServerVariables %><% = name %> <% = Request. ServerVariables(name) %><% Next %>11. File Global.asa:ứng dụng web = tập các trang Web, asp trong một th mục web và các th mục con.File Global.asa xác định khởi đầu và kết thúc của một ứng dụng web cũng nh của các session của từng user đơn thể đối với ứng dụng.File này cho phép đặt 4 thủ tục vào: Session_OnStart, Session_OnEnd,Application_OnStart, Application _OnEnd. Session_OnStart: thực hiện lần đầu tiên khi có một user yêu cầu trang web trong ứng dụng. (ứng với user đó) Session_OnEnd: thực hiện khi user thoát khỏi ứng dụng hoặc timeout. Application_OnStart: thực hiện 1 lần khi trang web đầu tiên của ứng dụng đợc chạy lần đầu tiên bởi bất kỳ user nào. Application _OnEnd: thực hiện một lần khi web server shutdown hoặc khi tất cả các session đã đóng.12. Các ph ơng thức và thuộc tíinh của một số đối t ợng: Reponse: Collection: Cookies, form, ChentCertificates, QueryString, ServerVariables Properties: Buffer, Charset, ContentType, Expires, ExpiresAbsolute, IsClientConnectied, Status, Pics, TotalByte. Method: AddHeadder, AppendToLog, BinaryWrite, Clear, End, Flush, Redirect, Write, BinaryRead. Server Properties: ScriptTimeout Method: CreateObject, HTMLEncode, MapPath, URLEncode. Application Collection: Contents, StaticObject. Method: Lock, Unlock Events: Application_OnStart, Application _OnEnd. Session Collection: Contents, StaticObject. Method: Abandon Properties: SessionID, TimeOut, CodePage, LCID Events: Session_OnStart, Session_OnEnd13. Sử dụng Cookies:Dùng đối tợng Request để nhận giá trị Cookies.Dùng đối tợng Reponse để đặt giá trị Cookies.6 Cookie có thể chỉ một giá trị, nếu nhiều giá trị thì phải dùng nhiều key.Ex:<% Reponse.Buffer = True %><% Dim dLastVisiteddLastVisited = Request.Cookies(LastVisit)If dLastVisited = Empty ThenReponse.Write Welcome! This is your first visitElseReponse.Write Welcome Back! <BR>Reponse.Write Your last visited on & dLastVisitedEnd IfReponse.Cookies(LastVisit) = Now()Reponse.Cookies(LastVisit).Expires = December 31,2000Session.Abandon %> Session.Abandon thoát khỏi session, không còn lại biến session nào.14. Gọi Stored Procedure trong ASP<% Set Cnn1 = Server.CreateObject(ADODB.Connection)StrCnn = driver = {SQL Server}; Server = smas; uid = sa; pwd= ; database= pubsCnn1.Open strCnnEt sp = CreateObject(ADODB.Command)Set sp.ActiveConnection = Cnn1Sp.CommandType = adCmdStoredProcSp.CommandText = sp_HelpSet pm = sp.CrateParameter(objname = 200, 1, 92, authors)Sp.parameters.Append pmSet rs = sp.Excute()Do Until rs is NothingReponse.Write <Table border = 1 bgColor = White><TR>Call PrintHeadingsCall PrintAllRecordsInRSReponse.Write </Table><BR><BR>Set rs=rs.NextRecordSetLoopCall CleanUp %><% Sub PrintHeadings()For each hdFld in rs.FieldsReponse.Write <TH> & hdFld.Name & </TH>NextReponse.Write <TR>End subSub printAllRecordsInRS()Do until rs.EOF7 For each fld in rs.FieldsReponse.Write <TD> & fldNextReponse.Write <TR>Rs.MoveNextLoopEnd SubSub CleanUp()Set rs = nothing Cnn1.CloseSet Cnn1 = nothingEnd sub %>Tóm lại các bớc thực hiện:- Tạo một kế nối Connection, active nó.- Tạo đối tợng kiểu Command, gán nó với một Connection đã kích hoạt (thuộc tính ActiveConnection), CommandText: tên thủ tục;- Tạo ta đối tợng tham số, bằng phơng thức CreateParameter để truyền tham số cho thủ tục.- Thực thi và sử dụng kết quả.15. Các hàm VBScript (1.0)Abs Asc Atn CboolCbyte Ccur Cdate CDblChr Clnt Cos CsngCstr Date DateSerial DateValueDay Exp Fix HexHour InputBox InStr Int IsArray IsDate IsEmpty IsNullIsNumeric IsObject LBound LcaseLeft Len Log LTrimMid Minute Month MsgBoxNow Oct Right RndRtim Second Sgn SinSpace Sqr StrComp TanTime TimeSerial TimeValue TrimUbound Ucase VarType WeekdayYear16. Gửi mailGửi mail theo giao thức SMTPDim objNewMailSet objNewMail = Server.CreateObject(CDONTS.NewMail)8 ObjNewMail.send sFromName, sToName, sSubject, sMsgSet objNewMail = nothing17.Các lệnh ASP và VBScript (1.0)Call Dim Do . loop EmptyErase Exit False For . nextIf . then . Else Nothing Null On ErrorOption Explicit Randomize Redim RemSelect case Set Sub TrueWhile .wend18. Các hằng (2.0)Color Comparion Date and TimeDate format File Input/Output MiscellaneousMsgbox String Var type19. Các hàm:Array Create Object DateAddDateDiff DateParl FilterFormatCurrency FormatDatetime FormatNumberFormatPercent GetObject InstrRevJoin LoadPicture MonthNameReplace RGB RoundScriptEngineMajorVersion ScriptEngineBuilVersion ScriptEngineScriptEngineMinorVersion Split StrReverseTypeName WeekDayName20. Các đối t ợng và hàm: (version 2.0) Object: Dictionary; FileSystemObject; TextStreamMethod:Add Close CreateTextFileFileExists Items KeyOpenTextFile Read ReadAllReadLine Remove RemoveAllSkip SkipLine WriteWriteBlankLines WriteLineCác properties:AtEndOfLine AtEndOfStream ColumnCompareMode Count HelpContext9 HelpFile Item KeyLineCác lệnh:Const PrivateFor each . Next Public21. Đối t ợng Error: (1.0) Properties: Decription, Number, SourceMethod: Clear, Raise22. VBScript 3.0 Collection: Drives, Files, Folders Constant: DriveType, SpecialFolder, File Attribute Properties:Attributes FileSystem ShareNameAvailableSpace FileSpace ShortNameDateCreated IsReady ShortPathDateLastAccessed IsRootFolder SizeDateLastModified Name SubFolderDrive ParentFolder TotalSizeDriveLetter Path TypeDrives RootFolder VolumeNameDriveType SerialNumberFiles Method:AddFolder BuildPath CopyCopyFile CopyFolder CreateFolderDelete DeleteFile DeleteFolderDriveExists FileExists FolderExistGetAbsolutePathName GetBaseName GetDriveGetDriveName GetExtensionName GetFileGetFileName GetFolder GetParentFolderNameGetSpecialFolder GetTempName MoveMoveFile MoveFolder OpenAsTextStream23. Sử dụng Transaction:Các yêu cầu: Dòng đầu tiên phải là: <% @TRANSACTION = REQUIRED%> Có thể điều chỉnh chấp nhận hoặc huỷe bỏ giao dịch bằng cách dùng SetComplete anh SetAbort từ đối tợng ObjectContext.10 [...]... Cookies. 6 1. Đặc điểm: Tên file: .asp Phải cài thêm Microsoft Active Server Page để bổ trợ cho Web Server, chuyên xử lý c¸c script viÕt trong file .asp. Cho phÐp viÕt øng dơng theo kiĨu Server Side => c¸c trang web sẽ sẽ đợc xử lý tại Server trớc khi gửi xuống Client. Các mà lệnh đợc chèn vào trong khắp trang web và đợc xử lý tuần tự. Mà lệnh là các Script, hiện ASP cho phép dùng 2 srcript là... kiểu Active X của ASP hay cài đặt thêm vào. Để lấy các giá trị truyền từ client lên dùng phơng thức request. Ex: s = request(Company) => Lấy giá trị của biến Company. 2. Sử dụng các đối t ợng: ASP cho phép sử dụng các đối tợng kiểu Active X. Để khai báo ta dùng phơng thức CreateObject của đối tợng Server cã s½n. Ex: Set f = Server.CreateObject(“Scripting.FileSystemObject”); Tỉng quan: Set param... thuéc tÝnh lµ Action vµ Method. Action quy định file ( .asp) mà sẽ đón nhận và xử lý dữ liệu đẩy lên. method quy định cách thức gửi dữ liệu; nếu là POST thì tất cả dữ liệu trong form sẽ đóng gói và đẩy lên Server; Nếu là GET thì dữ liệu đợc gửi đi nh một phần của URL, thờng là sau dấu ?. <Form Method = “POST” Action = “http://www.vnn.vn/data .asp >  KiĨu gưi d÷ liƯu GET cũng có thể lợi dụng để... phóng dùng Set f = nothing 3. Truy nhËp hÖ thèng file: <% Dim objFile Dim objStream Set objFile = Server.CreateObject(“Scripting.FileSystemObject”); Set objStream = objFile.OpenTextFile(Server.Mapath(“ /ASP ) &_ “\Chapter05\Listing 5-9\tips.txt”) Randomize Timer IntLine = Int(Rnd*19) 1 HelpFile Item Key Line Các lệnh: Const Private For each Next Public 21. Đối t îng Error: (1.0) Properties: Decription,...< % For each name in Request.ServerVariables %> <% = name %> <% = Request. ServerVariables(name) %> <% Next %> 11. File Global.asa: øng dơng web = tËp c¸c trang Web, asp trong mét th mục web và các th mục con. File Global.asa xác định khởi đầu và kết thúc của một ứng dụng web cũng nh của các session của từng user đơn thể đối với ứng dụng. File này cho phép đặt 4... thờng là sau dấu ?. <Form Method = “POST” Action = “http://www.vnn.vn/data .asp >  KiĨu gưi d÷ liƯu GET cũng có thể lợi dụng để gửi đi dới dạng mét link. < A href = “ http://www.vnn.vn/data .asp? name=ha&company=VASC” >Test</a>  Göi theo GET thì độ lớn bị hạn chế và không che dấu dữ liệu. Để lấy dữ liệu ta dùng phơng thức của đối tợng Request. S = Request.Form(Name) <=>... LOGON_USER, HTTP_USER_AGENT, ví dụ: Request.ServerVariables(LOGON_USER) Request.ServerVariables(HTTP_USER_AGENT) 9. Đối t ợng Reponse: Đối tợng này quản lý tất cả dữ liệu, nội dung sẽ đợc gởi cho Browser từ ASP. <% = Company%> <=> <% Reponse.Write Company %> Reponse cung cÊp 1 thuéc tÝnh lµ Expires, quy định thời gian (phút) mà trang Web chứa trong cache của IE. Vậy, nếu đặt dòng <% . Đặc điểm:Tên file: .asp Phải cài thêm Microsoft Active Server Page để bổ trợ cho Web Server, chuyên xử lý các script viết trong file .asp. Cho phép viết. Server có sẵn.Ex: Set f = Server.CreateObject(Scripting.FileSystemObject) ;Tổng quan: Set param = Server.CreateObject(PacketName.ClassName) ProgIDSau

Ngày đăng: 22/08/2012, 11:08

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan