Đang tải... (xem toàn văn)
• Nếu không có yêu cầu nào kể từ lần yêu cầu sau cùng một khoảng thời gian là <Timeout> phút, đối tượng Session mà Web server cấp cho lần làm việc đó sẽ tự động được giải phóng [r]
(1)Bài 2: Các lớp sử dụng ASP.NET
2.1 Request 2.2 Response 2.3 Cookies 2.4 Server 2.5 Session 2.6 Application
(2)2.1 Lớp Http Request
Khái niệm
Các thuộc tính
(3)Khái niệm
Request đối tượng ASP.NET, cho phép
(4)Các thuộc tính
RequestType Request.Form
Request.QueryString Cookies
(5)RequestType
Trả phương thức truyền liệu từ Client đến Server Gồm phương thức POST GET
Namespace: System.Web
Assembly: System.Web (in System.Web.dll) Type Value: System.String
Cú pháp:
(6)6 Request.Form
Form collection sử dụng để tập hợp liệu chứa
trong phần tử form chuyển từ Client đến Server bằng phương thức POST
Cú pháp:
Request.Form( element )[(index)|.Count];
(7)(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"] %>
(10) Request.Form.Count;
Trả số phần tử form chuyển từ Client đến Server
Request.Form.Keys[i];
Trả tên phần tử vị trí thứ i, i có giá trị từ đế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];
(12)Request.QueryString
Dùng để lấy liệu gửi từ Client đến Server
phương thức GET truyền 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ị giá trị trả tham số khi sử dụng Request.QueryString 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ử form
</Form>
<Form method=”Get” action=”FileName.aspx> Các phần tử form
</Form>
<a href=”FileName.aspx?var1=value1&var2=value2&…”> Text image
</a>
<a href=”FileName.aspx?var1=value1&var2=value2&…”> Text image
</a>
1
(14)Default.aspx
<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
<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
<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
<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
<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ả số phần tử form chuyển từ client đến server
Request.QueryString.Keys[i];
Trả tên phần tử vị trí thứ i, i có giá trị từ đến n-1
(20)2.2 Lớp Http Response
Khái niệm
Các thuộc tính
Các phương thức
(21)Khái niệm
Http Response sử dụng để truyền liệu từ webserver đến webBrowser
(22)Các thuộc tính
Buffer:
Quy định cách truyền tải liệu:
Response.Buffer=true/false;
True: Hồn tất cơng việc gửi lần
False: Thực xong đến đâu gửi đến đó
isClientConnected
Kiểm tra máy client có yêu cầu kết nối đến server
Response.isClientConnected=true/false;
(23)Các phương thức
Clear
End
Flush
Redirect
Write
• Xóa vùng tạm;
• Cú pháp: Response.Clear();
• Kết thúc tiến trình xử lý Server đẩy liệu tới Client;
• Cú pháp: Response.End();
• Kết thúc tiến trình, quay lại thực tiếp;
• Cú pháp: Response.Flush();
• Dùng để chuyển client sang URL khác;
(24)2.3 Lớp HttpCookies
Được sử dụng để ghi Cookies
Cookies asp.Net lớp Httpcookies Ví dụ:
Khởi tạo biến cookies:
Httpcookies varCk = new Httpcookies(“CkName”);
Ghi giá trị vào biến cookie: varCk.Value =value;
Server ghi vào Client biến Cookie: Response.Cookies.Add(varck);
Xóa Cookie: Response.Cookies.Clear(varck);
(25)Ví dụ:
<% string v, v1,v2,v3;
HttpCookie ckInform = new HttpCookie("Infor"); ckInform[“Us"] = "abc";
ckInform["Pwd"] = "xyz"; ckInform["Author"] = "123";
(26)26 Ví dụ:
<% string v, v1,v2,v3;
v = Request.Cookies[“Infor”].value ;
Hoặc:
(27)2.4 Lớp Http Server
Khái niệm
Các thuộc tính
(28)Khái niệm
Đối tượng Server cung cấp phương thức
giúp chuyển điều khiển trang với nhau, lấy thông tin mã lỗi, encode, …
Đối tượng Server cung cấp thông tin
Server cho ứng dụng
(29)Các thuộc tính
MachineName
ScriptTimeout
• Cho tên server
• Cú pháp: Server.MachineName(); • Thiết lập thời gian xử lý tối đa file
(30)Các phương thức MapPath Transfer HtmlEncode HtmlDecode 30
• Ánh xạ đường dẫn ảo thành đường dẫn vật lý cho tập tin Server
• Cú pháp: Server.MapPath(path);
• Gửi tất thơng tin mà xử lý từ trang ASP hành sang trang ASP khác
• Cú pháp: Server.Transfer(path); • Dùng để mã hố HTML thành chuỗi
• Cú pháp: Server.HTMLEncode(str); • Giải mã chuỗi thành HTML thành
• Cú pháp: Server.HTMLDecode(str);
• Ký tự < chuyển thành <
• Ký tự > chuyển thành >
• Ký tự & chuyển thành &
(31)2.5 Session
Khái niệm
(32)Khái niệm
Dùng để lưu trữ thông tin người dùng ứng
dụng
Thông tin lưu trữ Session người
dùng phiên làm việc cụ thể
Web Server tự động tạo một đối tượng Session cho
mỗi người dùng kết nối vào ứng dụng tự động hủy chúng người dùng cịn khơng làm việc với ứng dụng nữa
(33)Thuộc tính phương thức
Timeout Abandon
• Qui định khoảng thời gian (tính phút) mà Web Server trì đối tượng Session người dùng không gởi yêu cầu lại Server Giá trị mặc định thuộc tính 20 phút
• Nếu khơng có u cầu kể từ lần yêu cầu sau khoảng thời gian <Timeout> phút, đối tượng Session mà Web server cấp cho lần làm việc tự động giải phóng => Yêu cầu sau coi ngời dùng
Session.TimeOut = 100;
• Qui định khoảng thời gian (tính phút) mà Web Server trì đối tượng Session người dùng không gởi yêu cầu lại Server Giá trị mặc định thuộc tính 20 phút
• Nếu khơng có u cầu kể từ lần yêu cầu sau khoảng thời gian <Timeout> phút, đối tượng Session mà Web server cấp cho lần làm việc tự động giải phóng => Yêu cầu sau coi ngời dùng
Session.TimeOut = 100;
• Giải phóng vùng nhớ dùng để trì đối tượng Session Web Server gọi thực
(34)34 Thuộc tính phương thức
SessionID:
chứa ID của session kích hoạt,
user đựơc phân biệt sessionID gọi mã phiên làm việc
Count:
trả số session ứng dụng
Remove(“SessionName”):
xoá liệu biến “VarSession”
RemoveAll():
(35)Thuộc tính phương thức
Tạo biến Session:
Session.Add("Tên_Biến","Giá trị khởi tạo");
Đọc giá trị biến sesstion:
Session.Contents[“Tên_Biến”];
hoặc dùng số: Session.Contents[i];
Ghi (thay đổi) giá trị biến session:
(36)Thuộc tính phương thức
Các kiện tự động gọi phiên
làm việc tạo :
On_Start On_End
Các kiện đặt file Global.asax:
(37)Ví dụ:
Tại trang Login, người dùng nhập user name
mật :
Nếu : asp.net 123456 phép truy cập trang Home.aspx
Nếu sai : Thì nguyên trang Login.aspx
(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>
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") {
(40) Thiết kế Home.aspx Thiết kế Home.aspx.cs
40
<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
(42)2.6 Application
Khái niệm Thuộc tính
(43)Khái niệm
Đối tượng Application sử dụng để quản lý
tất thông tin ứng dụng web
Thông tin lưu trữ đối tượ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 số: Application.Contents[i];
string s = (string) Application[“chuoi”] ; int count = (int) Application[“count”] ;
(45) Ngồi ra, đối tượng Application cịn có phương thức
thường dùng :
Application.Lock(): Để khóa khơng cho người khác sửa đổi
các biến tồn cục
Application.UnLock() để mở khóa
Đối tượng Application có kiện :
Application_OnStart : kích hoạt lần
yêu cầu phát sinh
Application_OnEND : kích hoạt dịch vụ web dừng
(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 chúng tôi</h1> <asp:Label runat="server" ID="lblSLKhach"></asp:Label> </div>
(48)Index.aspx.cs
public partial class Index : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
lblSLKhach.Text = "Bạn 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 biến Applciation SLTruyCap khởi tạo giá trị 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 có người thăm Application.Contents["SLTruyCap"] =
(50)2.7 Chu trình sống trang web
Chu kỳ sống bắt đầu trình duyệt yêu cầu trang web gọi Session Chu kỳ sống tiếp tục nếu:
Session hoạt động
Người sử dụng tương tác với giao diện web kích hoạt kiện Dữ liệu trang (View State) wed gửi cho Server
Server nhận View State 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 người dùng duyệt web có kiện ứng dụng sau:
Application_Start: Người dùng duyệt trang web
Application_End: Khi khơng cịn người dùng duyệt trang web Application_Error: Khi có lỗi xảy ứng dụng
Session_Start: Khi người dùng duyệt trang web
Session_End: Khi người dùng đóng trình duyệt Session kết thúc (time
out)
(51)file Global.asax
<%@ Application Language="C#" %> <%@ Import Namespace="System.IO" %> <script runat="server">
void Application_Start(object sender, EventArgs e) {
//Kiểm tra chưa tồn file tạo file Count_Visited.txt if (!File.Exists(Server.MapPath("Count_Visited.txt")))
File.WriteAllText(Server.MapPath("Count_Visited.txt"), "0");
Application["DaTruyCap"] =int.Parse(File.ReadAllText(Server.MapPath("Count_Visited.txt"))); }
void Application_End(object sender, EventArgs e) {
}
void Application_Error(object sender, EventArgs e) {
}
void Session_Start(object sender, EventArgs e)
{ // Tăng số truy cập lên có khách truy cập if (Application["DangTruyCap"] == null)
Application["DangTruyCap"] = 1; else
Application["DangTruyCap"] = (int)Application["DangTruyCap"] + 1; // Tăng số truy cập lên có khách truy cập
Application["DaTruyCap"] = (int)Application["DaTruyCap"] + 1;
(52)Cảm ơn.