05-状态的传递和保持

通过Url传递

l 两个页面之间传递数据最好、后续麻烦最少、最简单的方法就是
通过Url传递。
l 案例:之间的增删改查页面
l 优点:简单,直接,明确知道发给谁,数据不会乱。缺点:如果
多个页面或者不确定页面之间要传那么就需要每次跳转都带着;
不保密。

无状态Http

l Http协议是无状态的,不会记得上次和网页“发生了什么”(故事《初
恋50次》)。试验:private 字段++。服务器不记的上次给了浏览器什
么,否则服务器的压力会太大,浏览器需要记住这些值,下次再提交服
务器的时候(请在我的宽度基础上增加10,)就要把上次的值提交给服
务器,让他想起来。如果要知道上一次的状态,一个方法是在对浏览器
响应结束之前将状态信息保存到页面表单中(实现一下),下次页面再
向服务器发出请求的时候带上这些状态信息,这样服务器就能根据这些
状态信息还原上次的状态了,类似于去看病的病历本。
l 尽量不要这么干,客户端的事情让客户端去做。
l 状态信息保存在隐藏字段中的缺点:加大网站的流量、降低访问速度、
机密数据放到表单中会有数据欺骗等安全性问题。故事:自行打印存折
,因为余额不是写到存折这个隐藏字段中的,唯一的关联就是卡号。要
把机密数据放到服务器,并且区别不同的访问者的私密区域,那么就要
一个唯一的标识。

Cookie

l 如果想自由的传递和读取,用Cookie。Cookie是和站点相关的,并且每次向服务器请
求的时候除了发送表单参数外,还会将和站点相关的所有Cookie都提交给服务器,是
强制性的。Cookie也是保存在浏览器端的,而且浏览器会在每次请求的时候都会把和
这个站点的相关的Cookie提交到服务器,并且将服务端返回的Cookie更新回数据库,
因此可以将信息保存在Cookie中,然后在服务器端读取、修改。服务器返回数据除了
普通的html数据以外,还会返回修改的Cookie,浏览器把拿到的Cookie值更新本地浏
览器的Cookie就可以。看报文
l 在服务器端控制Cookie案例,实现记住用户名的功能
• 设置值的页面:Response.SetCookie(new HttpCookie("UserName",
username));
• 读取值的页面:username= Request.Cookies["UserName"].Value;
l 如果不设定Expires那么生命周期则是关闭浏览器则终止,否则“最多”到Expires的
时候终止。
l Cookie的缺点:还不能存储过多信息,机密信息不能存。
l Cookie无法跨不同的浏览器。
l Cookie:是可以被清除,不能把不能丢的数据存到Cookie中;Cookie尺寸有限制,一
般就是几K,几百K。

Session原理

l 需要一种“服务器端的Cookie”:1、医生需要一个私人账本,
记录病人编号和身份的对应关系;2、为了防止病人根据分配给
他的编号猜测前后人的编号,那么需要一种“很难猜测”
l Cookie不能存储机密数据。如果想储存据,可以保存一个Guid
到Cookie中,然后在服务器中建立一个以Guid为Key,复杂数据
为Value全局Dictionary。放到Application中。代码见备注※。这
个Guid就是相当于用户的一个“令牌”
l ASP.Net已经内置了Session机制,把上面的例子用ASP.Net
Session重写。普通的HttpHandler要能够操作Session,要实现
IRequiresSessionState接口。
l Cookie是存在客户端,Session是存在服务器端,目的是一样的
:保存和当前客户端相关的数据(当前网站的任何一个页面都能
取到Session、Cookie)。
l Session(会话)有自动销毁机制,如果一段时间内浏览器没有
和服务器发生任何的交互,则Session会定时销毁。这也就是为
什么一段时间不操作,系统就会自动退出。
l Session实现登陆。

Application(*)

l Application是应用全局对象,被全体共享。操作之前先Lock,操
作完成后UnLock。
l 添加一个“全局应用程序类” Global.asax,当应用程序第一个
页面被访问的时候Application_Start执行。
举l 被很多书举烂了的例子“统计访问人数”,每次服务器上一个
内容被访问的时候Application_BeginRequest会执行就把数量++
。这样为什么不好?大并发访问会非常卡!
l 做网站开发尽量不要用Application,也很少有需要用它的时候。

总结

l 几种数据传递的区别和不同用途
• Application:全局数据,不要用
• Url:精准传递,用起来麻烦
• ••
隐藏字段:不保密
• Cookie:保存在客户端,不保密
• Session:保存在服务器端,不能放大数据


 

html:

<!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>
    <title></title>
</head>
<body>
<form action="CookiTest1.ashx" method="post">
    <input type="submit" name="Read" value="读" />
    <input type="submit" name="Write" value="写" />
    读出来的Cookie:$Model.Value
</form>
</body>
</html>
View Code
<!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>
    <title></title>
</head>
<body>
    <form action="HtttpNoZhuangTai.ashx" method="get">
        <input type="submit" value="增加" />
        <input type="hidden" name="Count" value="$Model.Count" />
        <p>$Model.Count</p>
    </form>
</body>
</html>
View Code
<!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>
    <title></title>
</head>
<body>
<form action="Login.ashx" method="post">
<table>
    <tr><td>用户名</td><td><input type="text" name="UserName" value="$Model.UserName" /></td></tr>
    <tr><td>密码</td><td><input type="password" name="Password"/></td></tr>
    <tr><td></td><td><input type="submit" name="Login" value="登录" /></td></tr>
</table>
</form>
</body>
</html>
View Code

服务器端:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NVelocity.App;
using NVelocity.Runtime;
using NVelocity;

namespace ZhuangTaiBaoChi
{
    public class CommonHelper
    {
        public static string RenderHtml(string name, object data)
        {
             VelocityEngine vltEngine = new VelocityEngine();
            vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file");
            vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("~/templates"));//模板文件所在的文件夹
            vltEngine.Init();

            VelocityContext vltContext = new VelocityContext();
            vltContext.Put("Model", data);//设置参数,在模板中可以通过$data来引用

            Template vltTemplate = vltEngine.GetTemplate(name);
            System.IO.StringWriter vltWriter = new System.IO.StringWriter();
            vltTemplate.Merge(vltContext, vltWriter);
            return vltWriter.GetStringBuilder().ToString();
        }
    }
}
View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ZhuangTaiBaoChi
{
    /// <summary>
    /// CookiTest1 的摘要说明
    /// </summary>
    public class CookiTest1 : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            //Request:请求。Response给客户端响应的
            context.Response.ContentType = "text/html";
            string read = context.Request["Read"];
            if (!string.IsNullOrEmpty(read))
            {
                HttpCookie cookie = context.Request.Cookies["Age"];
                string value = cookie.Value;
                var data = new { Value=value};
                string html = CommonHelper.RenderHtml("CookieTest1.htm", data);
                context.Response.Write(html);
            }
            else if (!string.IsNullOrEmpty(context.Request["Write"]))
            {
                //SetCookie(new HttpCookie("Age", "33")) Cookie生命周期是浏览器的生命周期
                //浏览器重启就自动删除了
                //context.Response.SetCookie(new HttpCookie("Age", "33"));

                HttpCookie cookie1 = new HttpCookie("Age", "33");
                cookie1.Expires = DateTime.Now.AddDays(1);
                context.Response.SetCookie(cookie1);
                context.Response.SetCookie(new HttpCookie("Name", "yzk"));
                string html = CommonHelper.RenderHtml("CookieTest1.htm", null);
                context.Response.Write(html);
            }
            else
            {
                string html = CommonHelper.RenderHtml("CookieTest1.htm", null);
                context.Response.Write(html);
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ZhuangTaiBaoChi
{
    /// <summary>
    /// HtttpNoZhuangTai 的摘要说明
    /// </summary>
    public class HtttpNoZhuangTai : IHttpHandler
    {
        //private int i = 1;

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";
            //i++;
            //string html = CommonHelper.RenderHtml("HttpNoZhuangTai.htm",
            //    new { Count=i});
            //context.Response.Write(html);

            //从病历本读出上次的值
            int count = Convert.ToInt32(context.Request["Count"]);
            count++;
            //新的值写入病历本
            string html = CommonHelper.RenderHtml("HttpNoZhuangTai.htm",
                new { Count=count});
            context.Response.Write(html);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ZhuangTaiBaoChi
{
    /// <summary>
    /// Login 的摘要说明
    /// </summary>
    public class Login : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";
            string login = context.Request["Login"];
            if (string.IsNullOrEmpty(login))
            {
                HttpCookie cookie = context.Request.Cookies["UserName"];
                string username;
                if (cookie == null)
                {
                    username = "";
                }
                else
                {
                    username = cookie.Value;
                }
                var data = new { UserName = username };
                context.Response.Write(CommonHelper.RenderHtml("Login.htm",data));
            }
            else
            {
                string username = context.Request["UserName"];
                HttpCookie cookie = new HttpCookie("UserName",username);
                cookie.Expires = DateTime.Now.AddDays(7);
                context.Response.SetCookie(cookie);
                context.Response.Write("登录成功");
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
View Code
原文地址:https://www.cnblogs.com/liuslayer/p/4770647.html