利用Application 和Session 对象分别对页面的值进行加一
首先看下页面部分的代码
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TestApplicationAndSession._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div>
Application和Session内置对象<br />
<br />
共同点:2个都是服务器内存变量,当机器重启或注销(准确说是IIS重新启动),变量的生命周期结束。<br />
<br />
说明:<br />
<br />
所有用户都可以使用Application对象,它的值是所有用户共享的。比如聊天信息,网站计数器等都使用Application对象。<br />
<br />
Session对象是针对单用户的,每一个用户都有自己的Session对象,各不相关。<br />
<br />
这里的用户概念(如果没有使用cookie):每打开一次浏览器,就是一个新用户。<br />
但是在打开的浏览器中转向另一个页面不是新用户。<br />
Application和Session使用方法:见后台代码部分。<br />
<br />
测试使用,设计用Application和Session分别完成加一功能:<br />
<br />
显示Application加一的结果:<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label><br />
<br />
显示Session加一的结果:<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label><br />
<br />
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="实现加一" /></div>
</form>
</body>
</html>
接下来看一下后台部分的代码
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
namespace TestApplicationAndSession
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
//Session["自己起的名称"]=任意类型变量;
if (Session["s"] == null)
{
//Session在赋值时,可以将任何类型直接赋值
Session["s"] = 1;
}
else
{
//Session在取值时要强制类型转换
int j = (int)Session["s"];
j++;
Session["s"] = j;
}
Label2.Text = Session["s"].ToString();
if (Application["a"] == null)
{
//因为Application是所有用户都可以访问
//在对Application写入时,一定要加锁
Application.Lock();
//Application在赋值时,可以将任何类型直接赋值
//Application["自己起的名称"] = 任意类型变量;
Application["a"] = 1;
//在对Application写入完成后,一定要解锁
Application.UnLock();
}
else
{
//Application在取值时要强制类型转换
int j = (int)Application["a"];
j++;
Application.Lock();
Application["a"] = j;
Application.UnLock();
}
Label1.Text = Application["a"].ToString();
}
}
}