登陆时,记住用户的账号密码

记住这些信息,能够使用Cookie来实现,更多Cookie应用,可参考http://www.cnblogs.com/insus/articles/2055310.html 或http://www.cnblogs.com/insus/articles/2055531.htmlhtml

如今咱们来模拟一个登陆介面:this

View Code
 <table>            <tr>                <td style="width: 15%; text-align: right;">                    User Name                </td>                <td>                    <asp:TextBox ID="TextBoxUserName" runat="server"></asp:TextBox>                </td>            </tr>            <tr>                <td style="text-align: right;">                    Password                </td>                <td>                    <asp:TextBox ID="TextBoxPassword" TextMode="Password" runat="server"></asp:TextBox>                </td>            </tr>            <tr>                <td style="text-align: right;">                    Remember me                </td>                <td>                    <asp:CheckBox ID="CheckBoxRememberMe" runat="server" />                </td>            </tr>            <tr>                <td style="text-align: right;">                </td>                <td>                    <asp:Button ID="ButtonLogin" runat="server" Text="Login" OnClick="ButtonLogin_Click" />                </td>            </tr>        </table>


运行时的效果:
3d

 

咱们要判断用户在点铵钮的Click事件时,是否有选择Remember me这个CheckBox,若是选中了,要把这个登陆的信息记录至Cookie,还要把Cookie的过时时间设置7天以后过时。反之,只把登陆的信息记录入Cookie之中,不设置Cookie的过时时间。能够参考下面的登陆事件代码:code

View Code
protected void ButtonLogin_Click(object sender, EventArgs e)    {        Response.Cookies["Name"].Expires = DateTime.Now.AddDays(-1);        Response.Cookies["Password"].Expires = DateTime.Now.AddDays(-1);        if (CheckBoxRememberMe.Checked)        {            Response.Cookies["Name"].Expires = DateTime.Now.AddDays(7);            Response.Cookies["Password"].Expires = DateTime.Now.AddDays(7);        }        Response.Cookies["Name"].Value = this.TextBoxUserName.Text.Trim();        Response.Cookies["Password"].Value = this.TextBoxPassword.Text.Trim ();    }


接下来,你还得在Page_load中去读取Cookie.server

View Code
 protected void Page_Load(object sender, EventArgs e)    {        if (!IsPostBack)        {            if (Request.Cookies["Name"] != null && Request.Cookies["Password"] != null)            {                this.TextBoxUserName.Text = Request.Cookies["Name"].Value;                this.TextBoxPassword.Attributes["value"] = Request.Cookies["Password"].Value;            }        }    }


看看操做演示,演示中有三种状态演示,第一种是没有点选CheckBox,这样的话,关闭窗口,下次再打开时,没有记住登陆的信息。
第二是点选择了CheckBox,这样下次再打开窗口,还能够看到账号与密码存储在相应的文本框中,这都是Cookie没有过时。
第三种,再点一次登陆,没有点选remember me的CheckBox,这样系统又移除了Cookie:htm

相关文章
相关标签/搜索