使用session实现登录判断功能

来源:互联网 发布:冰川网络官网 编辑:程序博客网 时间:2024/06/15 11:16

登录界面:

2个页面,一个index.aspx登录界面,一个view.aspx登录后的显示界面

如果一开始直接登录view.aspx,会显示没有登录,然后提示用户进入登录界面登录(index.aspx)


进入index.aspx界面注册:


如果用户名不为“winycg”,密码不为“123”,则显示用户名或密码不正确


输入用户名为“winycg”,密码为“123”,点击提交,跳转到view.aspx,显示登录成功


此时如果再次进入view.aspx界面后,还会显示登录成功,因为只要浏览器不关闭,session中存的值就不变


index.apsx代码://前台控件

<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>    <title></title>    <style type="text/css">        .auto-style1 {            width: 53%;        }    </style></head><body>    <form id="form1" runat="server">    <div>            <table class="auto-style1">            <tr>                <td>用户名:</td>                <td>                    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>                </td>            </tr>            <tr>                <td>密码:</td>                <td>                    <asp:TextBox ID="TextBox2" runat="server" TextMode="Password"></asp:TextBox>                </td>            </tr>            <tr>                <td>                    <asp:Button ID="Button1" runat="server" Text="提交" OnClick="Button1_Click"/>                </td>                <td> </td>            </tr>        </table>        </div>    </form></body></html>

index.apsx.cs代码:

protected void Page_Load(object sender, EventArgs e)        {        }        protected void Button1_Click(object sender, EventArgs e)        {            string name = TextBox1.Text.Trim();            string pwd = TextBox2.Text.Trim();            if(name=="")            {                Response.Write("<font color='red'>用户名不能为空</font>");                TextBox1.Focus();//获取焦点,光标会位于此处                return;            }            if(pwd=="")            {                Response.Write("<font color='red'>密码不能为空</font>");                TextBox2.Focus();                return ;            }            if(name=="winycg"&&pwd=="123")            {                Session["username"] = name;                Response.Redirect("view.aspx");            }            else            {                Response.Write("<font color='red'>用户名或密码不正确</font>");            }        }

view.aspx代码:

protected void Page_Load(object sender, EventArgs e)        {            if(Session["username"]==null)            {                Response.Write("<b><font color='red'>您不是合法用户!</font></b>");                Response.Write("<p><a href='index.aspx'>进入主页面</a>");            }            else            {                Response.Write("<b>恭喜登陆成功</b>");            }        }


1 0