本实例包括四个页面:登陆页(WebLogin.aspx)主页(Index.aspx) 页面跳转延迟页(ToIndex.htm)错误提示页(Error.aspx)
Web.config 页
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<sessionState timeout="1"/>
</system.web>
</configuration>
登陆页后台 代码:
public partial class WebLogin : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
if (txtUserName.Text == "admin" && txtPwd.Text == "888888")
{
if (SessionValue.svalue != null)
{
if (txtUserName.Text == SessionValue.svalue.ToString())
{
lbinfo.Text = "同一个账号已经登录,请先注销再尝试登录";
return;
}
}
if (Session.Keys.Count > 0)
{
foreach (string item in Session.Keys)
{
if (item == "username")
{
lbinfo.Text = "同一个账号已经登录,请先注销再尝试登录";
}
}
}
else
{// Session.Add("username", txtUserName.Text);正规的写法
Session["username"] = txtUserName.Text;
SessionValue.svalue = txtUserName.Text;
Response.Redirect("Index.aspx");
}
}
else
{
lbinfo.Text = "用户名或密码错误";
}
}
}
主页
后台代码:
public partial class Index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["username"] == null)
{
Response.Redirect("ToIndex.htm");
}
else
{
this.lbusername.Text = Session["username"].ToString();
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Session["username"] != null)
{
Response.Write(TextBox1.Text);
}
else
{
Response.Redirect("Error.aspx");
}
}
protected void btnvalidate_Click(object sender, EventArgs e)
{
//Session["username"] = null;
Session.Abandon();
SessionValue.svalue = "";
this.lbusername.Text = "";
}
}
页面跳转 延迟页:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="js/Jquery1.7.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
function toindex() {
window.location.href = "WebLogin.aspx";
}
setTimeout(toindex, 5000);
var count = 5;
function ChangeSecond() {
count--;
$('#sptime').text(count);
}
setInterval(ChangeSecond,1000);
})
</script>
</head>
<body>
<div>
您还没有登录,页面将在<span id="sptime">5</span>秒之内自动跳转到登录页面,如果页面没有自动跳转,请单击<a href="WebLogin.aspx">这里</a>
</div>
</body>
</html>
错误页:
提示:您长时间没有操作,导致会话超时,请重新登录。