登录时记住用户名和密码及cookie案例应用

文章原址:http://www.jb51.net/article/33588.htm

登录样子,可以参考某一论坛的登录介面:

 

记住这些信息,可以使用Cookie来实现,更多Cookie应用,可参考 http://jb51.net/article/33590.htm http://jb51.net/article/33591.htm 现在我们来模拟一个登录介面:

复制代码 代码如下:
<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>

运行时的效果:

 

 

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

复制代码 代码如下:
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.

复制代码 代码如下:
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:

 

转载于:https://www.cnblogs.com/ydfq-home/p/5017356.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值