ASP.NET学习笔记二

 一、Server对象

1)HTML标签的编码和解码

2)URL的编码和解码

5)虚拟路径

6)跨页面跳转

方式一:transfer和execute

方式二:使用查询字符串进行跨页信息传递

组装查询字符串:“main.aspx?userName=jack&pwd=123”

跳转界面:Response.Redirect(“main.aspx?userName=jack&pwd=123”);

接收数据的方式:Request.QueryString["userName"];
           Request.QueryString["pwd"];

方式三:使用按钮的跨页提交进行信息传递
设置按钮的PostBackUrl属性为要跳转的页面
此时在客户端 自动生成一段脚本,实现点击按钮的跳转操作,并且是以POST方式跳转

接收方式:
 Request.Form["name"]

TextBox txt=(TextBox)PreviousPage.FindControl("服务端ID")

前端代码:

<form id="form1" runat="server">
    <div>
        用户名:<asp:TextBox ID="userName" runat="server" /><br />
        密码:<asp:TextBox ID="pwd" runat="server" /><br />
        <asp:Button ID="btnSend" runat="server" Text="传递值" PostBackUrl="~/mainreceive3.aspx"/>
    </div>
    </form>

mainreceive3.aspx后端读取数据代码:

            //第一种方式:使用Request.Form[]:接收传递来的值
            //string userName = Request.Form["userName"];
            //string pwd = Request.Form["pwd"];
            //lblMsg.Text = "用户名:" + userName + ",密码:" + pwd;

            //第二种方式:PreviousPage:获得向当前页面传递控件的页
            Page page = PreviousPage;
            if (page != null)
            {
                //根据服务端ID搜索服务端控件,返回的是控件的基类型Control
                TextBox txtuserName = (TextBox)page.FindControl("userName");
                string userName = txtuserName.Text;

                TextBox txtPwd = (TextBox)page.FindControl("pwd");
                string pwd = txtPwd.Text;
                lblMsg.Text = "用户名:" + userName + ",密码:" + pwd;
            }

 

方式四:在任意事件处理程序中进行跨页面发送

//第二个参数:表示是否保留源页面中的form表单数据或querystring中的数据,true:保留,false:不保留
Server.Transfer("目标页",true)

接收方式:如果保留源页面中的form数据或查询字符串数据可以通过 Request.Form["name"]或Request.QueryString["name"]
 如果清空了源页面中form数据或查询字符串数据,可以这样接收
  TextBox txt=(TextBox)PreviousPage.FindControl("服务端ID")

二、状态管理

           1.视图状态

 作用:在单张页面的多次回传请求期间保存数据的方式。
 语法:
  ViewState属性是Control中定义的用来存储状态数据的属性
  保存数据:ViewState["key"]=value
  读取数据:object obj=ViewState["key"]
 原理:
  (1).当页面处理完毕后,视图状态中所有的信息会进行序列化操作,形成Base64编码的单个字符串保存在页面中id为__VIEWSTATE的隐藏域控件中,随着页面一起发回到客户端
  (2).当用户操作导致页面回传时此隐藏域中的信息会随着表单一起回发到服务器端,系统会将其内容还原为保存前的信息
 保存位置:客户端的隐藏域控件
 保存数据的类型:object类型
 注意:
  (1).如果通过视图状态保存的数据是对象类型,要将对象标记为可序列化Serializable
  (2).通过视图状态保存大量数据时,会占用网络带宽,影响下载速度

[Serializable]
    public class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
<form id="form1" runat="server">
    <div>
        <div>姓名:<asp:TextBox ID="txtName" runat="server" /></div>
        <div>年龄:<asp:TextBox ID="txtAge" runat="server" /></div>
        <div>
            <asp:Button ID="btnaddStudent" runat="server" Text="添加学员" OnClick="btnaddStudent_Click" />
        </div>
    </div>
    </form>
List<Student> lstStudents = null;//保存所有的学员
        protected void btnaddStudent_Click(object sender, EventArgs e)
        {
            //判断视图状态中有没有数据
            if (ViewState["lst"] != null)
                lstStudents = (List<Student>)ViewState["lst"];//从视图状态中获取数据,并进行类型转换
            else
                lstStudents = new List<Student>();
            string name = txtName.Text;
            int age =Convert.ToInt32(txtAge.Text);

            lstStudents.Add(new Student { Name = name, Age = age });

            foreach (Student item in lstStudents)
            {
                Response.Write("姓名:" + item.Name + "<br/>年龄:" + item.Age);
            }

            //学员集合保存至视图状态中
            ViewState["lst"] = lstStudents;

        }

 

2.应用程序状态管理

 作用:在web应用程序运行期间保存数据的方式
实现方式:2.1.使用Application实现
       语法:
       Application属性是Page类中定义的属性,返回的类型是HttpApplicationState类型的对象,这种类型的对象主要用来进行全局信息保存
       保存数据:Application[string name]=value
       读取数据:object obj=Application[name];
       保存位置:在服务器端的内存中
       保存数据的类型:object类型
       特点:
        (1)跨用户:任意用户写入的数据,其它的任意用户都能读取到
        (2)跨页面:在任意页面写入的数据,其它的任意页面都能读取到

       生命周期:
        保存数据,直到服务端重启或关闭

示例:登陆完成后,主界面显示最后登录的一个用户,并显示当前在线人数。

登陆界面前端代码:

<form id="form1" runat="server">
    <div>
        <div><label for="txtuserName">用户名:</label><asp:TextBox ID="txtuserName" runat="server" /></div>
         <div><label for="txtPwd">密码:</label><asp:TextBox ID="txtPwd" runat="server" /></div>
        <div>
            <asp:Button ID="btnLogin" runat="server" Text="登录" OnClick="btnLogin_Click" />
        </div>
    </div>
    </form>

                    主界面前端代码:

<form id="form1" runat="server">
    <div>
        <asp:Label ID="lblCurrentUser" runat="server" /><br />
        <asp:Label ID="lblOnLine" runat="server" />
    </div>
    </form>

登录界后端代码:

List<User> lstUsers = null;
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            string userName = txtuserName.Text;
            string pwd = txtPwd.Text;
            //...省略判断用户名和密码是否正确
            if (Application["lst"] != null)
            {
                //从Application中读取数据,并转换为List泛型集合
                lstUsers = (List<User>)Application["lst"];
            }
            else
            {
                lstUsers = new List<User>();
            }
            //把此次登录成功的用户对象保存至集合中
            lstUsers.Add(new User { UserName = userName, Password = pwd });

            //由于Application对象是全局对象,可能有多个用户同时操作它,为了避免发生并发性冲突
            //当某个用记操作它时,将其进行加锁,其它用户就无法操作
            Application.Lock();
            //把最后登录成功的用户名存储至Application中
            Application["lastUserName"] = userName;

            //将所有的在线人员集合保存至Application中
            Application["lst"] = lstUsers;
            //操作完成后,解锁
            Application.UnLock();
            Response.Redirect("~/Main.aspx");//跳转至主页面
        }

主界面后端代码:

protected void Page_Load(object sender, EventArgs e)
        {
            Global.WriteLog("Main页面加载完成");

            if (Application["lastUserName"] != null && Application["lst"]!=null)
            {
                //Application中根据指定的name去获取数据
                string lastUserName = Application["lastUserName"].ToString();
                lblCurrentUser.Text = "最后登录的用户是:" + lastUserName;

                List<User> lstUsers = (List<User>)Application["lst"];
                lblOnLine.Text = "当前在线人员有:"+lstUsers.Count+"人<br/>";
                foreach (User item in lstUsers)
                {
                    lblOnLine.Text += item.UserName + "<br/>";
                }
            }
        }

 

实现方式:2.2.通过Global类的静态属性实现
       语法:
        (1)在项目中添加一个Global.asax文件,有一个全局类Global,继承自HttpApplication
        (2)在Global类中定义静态属性,如果需要对属性初始化,则在Application_Start()事件处理中执行
        (3)写入数据:Global.静态属性=值
        (4)读取数据:Global.静态属性
       保存位置:在服务器端的内存中
       特点:
        (1)跨用户:任意用户写入的数据,其它的任意用户都能读取到
        (2)跨页面:在任意页面写入的数据,其它的任意页面都能读取到

       生命周期:
        保存数据,直到服务端重启或关闭

示例:登陆完成后,主界面显示最后登录的一个用户,并显示当前在线人数。

Global.asax.cs代码:

public static string LastUserName { get; set; }//保存最后登录成功的用户名
        public static List<User> ListUsers { get; set; }//保存所有的在线用户列表

        /// <summary>
        /// 记录操作日志
        /// </summary>
        /// <param name="exe">日志内容</param>
        public static void WriteLog(string exe)
        {
            string path = @"f:\web.log";
            using (StreamWriter sw = File.AppendText(path))
            {
                DateTime now = DateTime.Now;
                string content = now.ToLongTimeString() + " :" + now.Millisecond + "  :执行操作:" + exe;
                sw.WriteLine(content);
            }
        }
       
        // 应用程序启动时触发          
        protected void Application_Start(object sender, EventArgs e)
        {
            //由于此处的代码是最早且仅被执行一次的代码
            //所以可以将用户列表集合的初始化放在此处
            ListUsers = new List<Demo001.User>();
            WriteLog("应用程序启动");
        }

        //会话启动时触发
        protected void Session_Start(object sender, EventArgs e)
        {
            WriteLog(Session.SessionID + "会话创建");
        }

        //开始请求页面时触发
        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            WriteLog("开始请求:" + Request.RawUrl);
        }

        //启用身份验证时触发
        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        //应用程序出错时触发
        protected void Application_Error(object sender, EventArgs e)
        {

        }

        //会话结束时触发
        protected void Session_End(object sender, EventArgs e)
        {
            WriteLog(Session.SessionID + "会话结束");
        }

        //应用程序结束时触发
        protected void Application_End(object sender, EventArgs e)
        {
            WriteLog("应用程序结束");
        }

 

3.会话级别状态管理

 作用:保存特定用户的特有的信息,比如用户的权限,密码,个性化设置等。
实现方式:3.1使用Session保存用户的信息
 语法:
  Session属性是Page类中的属性,返回的类型是HttpSessionState类型的对象,这种类型的对象是用来保存特定用户的信息
  保存数据:Session[string name]=value
  读取数据:object obj=Session[name]
 
 保存位置:为每一个Session在服务端单独开辟内存,保存它的数据
 特点:
  (1)跨页面:在任意页面写入的数据,其它的任意页面都能读取到
  (2)不跨用户:每个用户只能访问自己保存的数据

 会话的超时时间:
  默认会话的超时时间是20分钟
  设置它的超时时间: 
   (1)Session.Timeout=数值; 单位是分钟
   (2)在web.config中
    <system.web>
     <sessionState timeout="1"/>
    </system.web>
 用户主动释放会话:
  Session.Abandon()

4.Cookies对象

特点:跨页面,不跨用户。

 

 

 

 定义Cookies对象

            //创建cookie对象
            HttpCookie hcuser = new HttpCookie("user");
            //设置cookie保存的值
            hcuser.Value = userName;
            //设置cookie对象过期时间,将其设置为持久型cookie,否则它是临时性cookie
            hcuser.Expires = DateTime.Now.AddDays(100);

            //由服务端将数据写入客户端的cookie中
            Response.Cookies.Add(hcuser);

            //判断是否选择了十天内免登录
            if (chkRemberMe.Checked)
            {
                HttpCookie hcpwd = new HttpCookie("pwd");
                hcpwd.Value = pwd;
                hcpwd.Expires = DateTime.Now.AddDays(10);
                Response.Cookies.Add(hcpwd);
            }

读取Cookies:

            //在服务端读取客户端中的cookie数据
            HttpCookie hc = Request.Cookies["user"];

 

 总结:

 

ViewState

Application

Session

Cookie

保存内容类型

可序列化类型

任意object

任意object

string

储存位置

页面隐藏域中

服务器端内存

服务器端内存

客户端内存或硬盘

生命周期

页面回传过程中

声明至应用程序关闭

声明至会话结束

声明至浏览器关闭或过期

跨页面性

不跨页面

跨页面

跨页面

跨页面

跨用户性

不跨用户

跨用户

不跨用户

不跨用户

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2020-12-24 20:12  ☞@_@  阅读(118)  评论(0编辑  收藏  举报