在B/S應用程序中,前台與后台的數據交互,都是通過HTML中form表單完成的。form提供了兩種數據傳輸的方式:get和post,用個“登錄”這個例子來簡單理解二者提交和獲取方式的不同。
提交
在HTML中寫post方式提交
/p>
"http://www.w3.org/TR/html4/loose.dtd">
登錄用戶名: | |
密 碼: | |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
namespace LoginTest
{
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//定義兩個變量,獲取從表單上提交的用戶名和密碼
string userName = Request.Form["userName"].ToString();
string userPwd = Request.Form.Get("userPwd").ToString();
//連接數據庫
SqlConnection con = new SqlConnection("Server=.;database=login;uid=sa;pwd=123456");
con.Open();
//用一個命令對象去查找數據庫中這個用戶是否存在
SqlCommand cmd = new SqlCommand("select count(*) from login where userName='" + userName + " 'and userPwd='" + userPwd + "' ", con);
//判斷用戶是否存在
int count = Convert.ToInt32(cmd.ExecuteScalar());
if (count > 0)
{
//用戶存在
Response.Redirect("main.aspx?userName=" + userName); //get提交
//Response.Redirect("main.aspx"); //post提交
}
else
{
//用戶不存在
Response.Redirect("loginFail.html");
}
}
}
}
獲取
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace LoginTest
{
public partial class main : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//get提交,獲取用戶名的方法
string userName = Request.QueryString["userName"].ToString();
//由服務器端向客戶端書寫
Response.Write("歡迎" + userName + "光臨天貓購物"); //get提交所用的獲取方法
// Response.Write("歡迎光臨天貓購物"); //post提交所用的獲取方法
}
}
}
get提交的時候,它的變量和值都會在地址欄里顯示出來,它的安全性有一定的影響。從一個頁面到另一個頁面傳參的時候,可以使用get方法,速度更快些。
總結
1、get是用來從服務器上獲得數據,而post是用來向服務器上傳遞數據。
2、get在傳輸過程,表單中數據的按照variable=value的形式,添加到action所指向的URL后面,並且兩者使用“?”連接,數據被放在請求的URL中,服務器會將請求URL記錄到日志文件中,然后放在某個地方,這樣就可能會有一些隱私的信息被第三方看到。另外,用戶也可以在瀏覽器上直接看到提交的數據,一些系統內部消息將會一同顯示在用戶面前。而post是將表單中的數據放在form的數據體中,其所有操作對用戶來說都是不可見的。
總之,個人對於get和post的理解,最大的不同就是一個用於獲取數據,一個用於修改數據。