1 / 52

Bài 2: Các lớp sử dụng trong ASP.NET

Bài 2: Các lớp sử dụng trong ASP.NET . 2.1 . Request 2.2 . Response 2.3 . Cookies 2.4 . Server 2.5 . Session 2.6. Application 2.7. Chu trình sống của một trang web . 2.1 Lớp Http Request. Khái niệm Các thuộc tính. Khái niệm.

talisa
Télécharger la présentation

Bài 2: Các lớp sử dụng trong ASP.NET

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Bài 2: Các lớp sử dụng trong ASP.NET 2.1. Request 2.2. Response 2.3. Cookies 2.4. Server 2.5. Session 2.6. Application 2.7. Chu trìnhsốngcủamộttrang web

  2. 2.1 Lớp Http Request • Khái niệm • Các thuộc tính

  3. Khái niệm • Request là một đối tượng của ASP.NET, nó cho phép đọc các thông tin do các trang khác gửi (Submit) đến

  4. Các thuộc tính • RequestType • Request.Form • Request.QueryString • Cookies

  5. RequestType • Trả về phương thức truyền dữ liệu từ Client đến Server • Gồm 2 phương thức POST và GET • Namespace:  System.Web • Assembly:  System.Web (in System.Web.dll) • Type Value: System.String • Cú pháp: public string RequestType { get; set; }

  6. Request.Form • Form collection sử dụng để tập hợp dữ liệu được chứa trong các phần tử của form chuyển từ Client đến Server bằng phương thức POST • Cú pháp: Request.Form( element )[(index)|.Count]; Request.Form.Keys[i];

  7. Ví dụ 1 - Request.Form( element )

  8. Default.aspx <body> <form method= "post" action= "CheckUser.aspx" > UserName: <input type="text" name="txtUser" /><br /> Password: <input type="password" name="txtPwd" /><br /> <input type= "submit" name="btnLogin" value="Login" /><br /> </form> </body>

  9. CheckUser.aspx <body> <b>UserName:</b> <% =Request.Form["txtUser"] %><br /> <b>Password:</b> <% =Request.Form["txtPwd"] %> </body>

  10. Request.Form.Count; • Trả về số phần tử của form chuyển từ Client đến Server • Request.Form.Keys[i]; • Trả về tên của phần tử tại vị trí thứ i, trong đó i có giá trị từ 0 đến n-1 • với n=Request.Form.Count

  11. CheckUser.aspx <body> <div> <b>UserName:</b> <%=Request.Form["txtUser"] %><br/> <b>Password:</b> <%=Request.Form["txtPwd"] %> <br /> <b>Số phần tử:</b> <%=Request.Form.Count %> <br/> <% int i, num; string s1; num = Request.Form.Count; for (i = 0; i < num; i++) { s1 = Request.Form.Keys[i]; Response.Write(Request.Form[s1]); } %> </div> </body>

  12. Request.QueryString • Dùng để lấy dữ liệu được gửi từ Client đến Server bằng phương thức GET hoặc truyền dữ liệu có chứa tag liên kết <a> Hyperlink http://<host>[:<port>][<path>[?<QueryString>]] [?Tham_so_1=gia_tri_1[&Tham_so_2=gia_tri_2[&……]]] Nếu tham số không có giá trị thì giá trị trả về của tham số khi sử dụng Request.QueryString là NULL • Cú pháp: Request.QueryString( variable )[(index)|.Count]

  13. Cách truyền tham số <Form method=”Get” action=”FileName.aspx> Các phần tử của form </Form> 1 <a href=”FileName.aspx?var1=value1&var2=value2&…”> Text hoặc image </a> 2

  14. Default.aspx 1 <body> <div> <form method= "get" action= "CheckUser.aspx" > UserName: <input type="text" name="txtUser" /><br /> Password: <input type="password" name="txtPwd" /><br /> <input type= "submit" name="btnLogin" value="Login" /><br /> </form> </div> </body>

  15. CheckUser.aspx 1 <body> <% string strUser, strPws; strUser = Request.QueryString["txtUser"]; strPws = Request.QueryString["txtPwd"]; %> <b>UserName: </b> <%=strUser%> <br /> <b>Password: </b> <%=strPws %> </body>

  16. Default.aspx 2 <body> <form method= "post" action= "CheckUser.aspx" > UserName: <input type="text" name="txtUser" /><br /> Password: <input type="password" name="txtPwd" /><br /> <input type= "submit" name="btnLogin" value="Login" /><br /> </form> <a href= "News.aspx">Tin tức</a><br /> <a href= "News.aspx">Âm nhạc</a><br /> </body>

  17. CheckUser.aspx 2 <body> <a href="News.aspx?Id=3456&type=hide"> Tin tuc</a> <br/> <a href="News.aspx?Id=36586&type=item">Music</a><br/> <% string strUser, strPws; strUser = Request.QueryString["txtUser"]; strPws = Request.QueryString["txtPwd"]; %> <b>UserName: </b> <%=strUser%> <br /> <b>Password: </b> <%=strPws %> </body>

  18. New.aspx 2 <body> <% String strID, strType; strID= Request.QueryString["Id"]; strType= Request.QueryString["type"]; %> Ban chon ma so : <%=strID%><br/> Kieu hien thi : <%=strType%><br/> </body>

  19. Request.QueryString.Count; • Trả về số phần tử của form chuyển từ client đến server • Request.QueryString.Keys[i]; • Trả về tên của phần tử tại vị trí thứ i, trong đó i có giá trị từ 0 đến n-1 • Với n=Request.QueryString.Count

  20. 2.2 Lớp Http Response • Khái niệm • Các thuộc tính • Các phương thức

  21. Data Khái niệm Http Response được sử dụng để truyền dữ liệu từ webserver đến webBrowser

  22. Cácthuộctính • Buffer: • Quyđịnhcáchtruyềntảidữliệu: • Response.Buffer=true/false; • True: Hoàntấtcôngviệcvàgửimộtlần • False: Thựchiệnxongđếnđâuthìgửiđếnđó • isClientConnected • Kiểmtramáy client cóyêucầukếtnốiđến server • Response.isClientConnected=true/false;

  23. Cácphươngthức • Clear • End • Flush • Redirect • Write • Xóavùngtạm; • Cúpháp: Response.Clear(); • Kếtthúctiếntrìnhxửlýtrên Server vàđẩydữliệutớiClient; • Cúpháp: Response.End(); • Kếtthúctiếntrình, quay lạithựchiệntiếp; • Cúpháp: Response.Flush(); • Dùngđểchuyển client sang một URLkhác; • Cúpháp: Response.Redirect(url, boolean); • Dùngđểghidữliệura web; • Cúpháp: Response.Write(strname); • Hoặc <% = strname%>

  24. 2.3 LớpHttpCookies • ĐượcsửdụngđểghiCookies • Cookies trongasp.Netở lớpHttpcookies • Vídụ: • Khởitạobiến cookies: HttpcookiesvarCk= new Httpcookies(“CkName”); • Ghigiátrịvàobiến cookie: varCk.Value=value; • Server ghivào Client mộtbiến Cookie: Response.Cookies.Add(varck); • Xóa Cookie: Response.Cookies.Clear(varck);

  25. Ví dụ: <% string v, v1,v2,v3; HttpCookieckInform = newHttpCookie("Infor"); ckInform[“Us"] = "abc"; ckInform["Pwd"] = "xyz"; ckInform["Author"] = "123"; Response.Cookies.Add(ckInform); %>

  26. Ví dụ: <% string v, v1,v2,v3; v = Request.Cookies[“Infor”].value ; Hoặc: v1 = Request.Cookies[“Infor”] [“Us”]; v2 = Request.Cookies[“Infor”] [“Pwd”]; v3 = Request.Cookies[“Infor”] [“Author”]; %>

  27. 2.4 Lớp Http Server • Kháiniệm • Cácthuộctính • Cácphươngthức

  28. Kháiniệm • Đốitượng Servercungcấpcácphươngthứcgiúpchuyểnđiềukhiểngiữacáctrangvớinhau, lấythông tin vềmãlỗi, encode, … • Đốitượng Servercungcấpthông tin của Server choứngdụng

  29. Cácthuộctính • MachineName • ScriptTimeout • Cho tên server • Cúpháp: Server.MachineName(); • Thiếtlậpthờigianxửlýtốiđa 1 file • Cúpháp: Server.ScriptTimeout=100s;

  30. Cácphươngthức • MapPath • Transfer • HtmlEncode • HtmlDecode • Ánhxạđườngdẫnảothànhđườngdẫnvậtlýchomộttập tin trênServer • Cúpháp: Server.MapPath(path); • Gửitấtcảthông tin mànóđãxửlýtừtrang ASP hiệnhành sang trang ASP khác • Cúpháp: Server.Transfer(path); • Dùng để mã hoá HTML thành chuỗi • Cúpháp: Server.HTMLEncode(str); • Ký tự < chuyển thành &lt; • Ký tự > chuyển thành &gt; • Ký tự & chuyển thành &amp; • Dấu đôi “ chuyển thành &quot; • Giải mã các chuỗi thành HTML thành • Cúpháp: Server.HTMLDecode(str);

  31. 2.5 Session • Khái niệm • Thuộc tính và phương thức

  32. Khái niệm • Dùng để lưu trữ thông tin của người dùng trong ứng dụng • Thông tin được lưu trữ trong Session là của một người dùng trong một phiên làm việc cụ thể • Web Server sẽ tự động tạo một đối tượng Session cho mỗi người dùng mới kết nối vào ứng dụng và tự động hủychúng nếu người dùng còn không làm việc với ứng dụng nữa

  33. Thuộc tính và phương thức • Timeout • Abandon • Qui định khoảng thời gian (tính bằng phút) mà Web Server duy trì đối tượng Session nếu người dùng không gởi yêu cầu nào về lại Server. Giá trị mặc định của thuộc tính này là 20 phút • Nếukhôngcóyêucầunàokểtừlầnyêucầusaucùngmộtkhoảngthờigianlà <Timeout> phút, đốitượng Session mà Web server cấpcholầnlàmviệcđósẽtựđộngđượcgiảiphóng => Yêucầusaucoinhưngờidùngmới • Session.TimeOut = 100; • Giảiphóngvùngnhớđượcdùngđểduytrìđốitượng Session trên Web Server ngaykhiđượcgọithựchiện • Nhữngyêucầusauđóđược Web server coinhưlàmộtngườidùngmới • Session.Abandon();

  34. Thuộc tính và phương thức • SessionID: • chứa ID củasession đangkíchhoạt, mỗi user đựơcphânbiệtbởisessionIDgọilàmãphiênlàmviệc • Count: • trảvềsố session trongmộtứngdụng • Remove(“SessionName”): • xoádữliệutrênbiến “VarSession” • RemoveAll(): • Xoádữliệu, nhưngsessionIDvẫntồntại

  35. Thuộc tính và phương thức • Tạo biến Session: Session.Add("Tên_Biến","Giá trị khởi tạo"); • Đọc giá trị của một biến sesstion: Session.Contents[“Tên_Biến”]; hoặc dùng chỉ số: Session.Contents[i]; • Ghi (thay đổi) giá trị của biến session: Session.Contents[“Tên_Biến”] = <Giá trị mới>;

  36. Thuộc tính và phương thức • Các sự kiện tự động được gọi mỗi khi một phiên làm việc được tạo ra : • On_Start • On_End • Các sự kiện được đặt trong file Global.asax:

  37. Vídụ: • Tại trang Login, người dùng nhập user name và mật khẩu : • Nếu đúng : asp.net và 123456 thì được phép truy cập các trang Home.aspx • Nếu sai : Thì ở nguyên trang Login.aspx • Trang Home.aspx (chỉ có 1 dòng giới thiệu)

  38. Thực hiện • Thiết kế Login.aspx : • Trang Login.aspx • Trang Login.aspx.cs • Thiết kế Home.aspx : • Thiết kế Home.aspx • Thiết kế Home.aspx.cs • Thiết kế Golbal.asax :

  39. Trang Login.aspx • Trang Login.aspx.cs <head runat="server"> <title>Login</title> </head> <body> <form id="form1" runat="server"> User name: <asp:TextBox runat="server" ID="txtUserID"> </asp:TextBox><br /> Password: <asp:TextBox runat="server" ID="txtPassword" TextMode="Password"> </asp:TextBox> <br /> <asp:Button runat="server" Text="Login" ID="cmdLogin" onclick="cmdLogin_Click"/> </form> </body> </html> public partial class Login : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void cmdLogin_Click(object sender, EventArgs e) { if (txtUserID.Text == "asp.net" && txtPassword.Text == "123456") { Session.Contents["TrangThai"] = "DaDangNhap"; Response.Redirect("Home.aspx"); } } }

  40. Thiết kế Home.aspx • Thiết kế Home.aspx.cs <head runat="server"> <title>Home</title> </head> <body> <form id="form1" runat="server"> <div> <h1 style="text-align:center"> bạn đã đăng nhập thành công </h1> </div> </form> </body> public partial class Home : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (Session.Contents["trangthai"].ToString()=="chuadangnhap") { Response.Redirect ("Login.aspx"); } } }

  41. Thiết kế Golbal.asax <script runat="server"> void Application_Start(object sender, EventArgs e) {// Code that runs on application startup} void Application_End(object sender, EventArgs e) {// Code that runs on application shutdown} void Application_Error(object sender, EventArgs e) { // Code that runs when an unhandled error occurs} void Session_Start(object sender, EventArgs e) {// Code that runs when a new session is started Session.Add("TrangThai", "chuadangnhap"); } void Session_End(object sender, EventArgs e) {// Code that runs when a session ends. // Note: The Session_End event is raised only when the sessionstate mode // is set to InProc in the Web.config file. If session mode is set to StateServer // or SQLServer, the event is not raised.} </script>

  42. 2.6 Application • Khái niệm • Thuộc tính

  43. Khái niệm • Đối tượng Application được sử dụng để quản lý tất cả các thông tin của một ứng dụng web • Thông tin được lưu trữ trong đối tượng Application có thể được xử lý trong bất kỳ trang aspx nào trong suốt chu kỳ sống của ứng dụng

  44. Tạo biến Application: Application.Add(“Tên_Biến”, <Giá trị khởi tạo>); • Truy xuất đến biến Application: Application.Contents[“Tên_Biến”] ; hoặc chỉ số: Application.Contents[i]; string s = (string) Application[“chuoi”] ; int count = (int) Application[“count”] ;

  45. Ngoài ra, đối tượng Application còn có 2 phương thức thường dùng là : • Application.Lock(): Để khóa không cho người khác sửa đổi các biến toàn cục • Application.UnLock() để mở khóa • Đối tượng Application cũng có 2 sự kiện : • Application_OnStart : chỉ được kích hoạt duy nhất một lần khi yêu cầu đầu tiên phát sinh • Application_OnEND: được kích hoạt khi dịch vụ web dừng (unload) • Mã lệnh viết cho 2 sự kiện này cũng được đặt trong file Global.asax

  46. Vídụ: • Đếm số lượng khách truy cập website • Giải quyết: • Tạo website index.aspx • Sử dụng Application

  47. Index.aspx <head runat="server"> <title>Index</title> </head> <body> <form id="form1" runat="server"> <div> <h1>Chào mừng bạn đã đến website của chúng tôi</h1> <asp:Label runat="server" ID="lblSLKhach"></asp:Label> </div> </form> </body>

  48. Index.aspx.cs public partial class Index : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { lblSLKhach.Text = "Bạn là vị khách thứ : " + Application.Contents["SLTruyCap"].ToString(); } }

  49. Golbal.asax void Application_Start(object sender, EventArgs e) { // Code that runs on application startup //Tạo một biến Applciation là SLTruyCap và khởi tạo giá trị 0 Application.Add("SLTruyCap", 0); } void Session_Start(object sender, EventArgs e) { // Code that runs when a new session is started //Tăng số lượng người truy cập lên 1 khi có một người mới thăm Application.Contents["SLTruyCap"] = int.Parse(Application.Contents["SLTruyCap"].ToString()) + 1; }

  50. 2.7 Chu trìnhsốngcủamộttrang web • Chu kỳ sống được bắt đầu khi trình duyệt yêu cầu một trang web gọi là Session.  • Chu kỳ sống vẫn tiếp tục nếu: • Session đang hoạt động.  • Người sử dụng tương tác với giao diện web cho đến khi kích hoạt một sự kiện.  • Dữ liệu của trang (View State) wed được gửi về cho Server.  • Server nhận được View State và trả lại yêu cầu từ View State.  • Chu kỳ sống kết thúc khi:  • Người dùng kết thúc trình duyệt.  • Session kết thúc (timeout). • Mỗi khi người dùng duyệt web của mình sẽ có các sự kiện ứng dụng sau: • Application_Start: Người dùng đầu tiên duyệt trang web.  • Application_End: Khi không còn người dùng nào duyệt trang web.  • Application_Error: Khi có lỗi xảy ra trong ứng dụng  • Session_Start: Khi người dùng duyệt một trang web  • Session_End: Khi người dùng đóng trình duyệt hoặc Session kết thúc (time out)

More Related