• 创建cookie


    《ASP.NET 3.5揭秘》读书笔记

    cookie 分为:会话cookie和持久化cookie两种。

    会话cookie只存在于内存中;

    持久化cookie可以存在几个月甚至几年,持久化cookie创建后,会被浏览器长久地保存在用户的电脑上。(如IE存在这个文件夹里:\Documents and Settings\[user]\Cookies)

    创建会话cookie。

    通过Response.Cookies集合添加cookie来创建新的cookie。

    <%@ Page Language="C#" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <script runat="server">
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            Response.Cookies["message"].Value = txtCookieValue.Text; 
        }
    </script>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>Set Cookie</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
        
        <asp:Label
            id="lblCookieValue"
            Text="Cookie Value:"
            AssociatedControlID="txtCookieValue"
            Runat="server"/>
        <asp:TextBox
            id="txtCookieValue"
            Runat="server" />
        <asp:Button
            id="btnAdd"
            Text="Add Value"
            OnClick="btnAdd_Click"
            Runat="server"/>
        </div>
        </form>
    </body>
    </html>

    创建持久cookie。

    如果希望创建持久化cookies,则需要为cookie指定一个过期时间。如下面程序中Respo.Cookies["counter"].Expires = DataTime.Now.AddYears(2);

    <%@ Page Language="C#" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <script runat="server">
        void Page_Load()
        {
             // Get current value of cookie
            int counter = 0;
            if (Request.Cookies["counter"] != null)
            {
                counter = Int32.Parse(Request.Cookies["counter"].Value);
            }
            
            // Increment counter
            counter++;
            
            // Add Peristent cookie to browser
            Response.Cookies["counter"].Value = counter.ToString();
            Response.Cookies["counter"].Expires = DateTime.Now.AddYears(2);
            
            // Display value of counter cookie
            lblCounter.Text = counter.ToString();
        }
    </script>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>Set Persister Cookie</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
        
        You have visited this page
        <asp:Label
            id="lblCounter"
            Runat = "server" />
        times!
        </div>
        </form>
    </body>
    </html>
  • 相关阅读:
    java当前时间
    @Repository、@Service、@Controller 和 @Component
    spring mvc controller间跳转 重定向 传参
    MVC思想
    AJAX
    MySQL优化大总结
    MySQL数据库优化
    java JDBM2 的几个简单实例
    集群环境下如何防止定时任务重复执行?
    Java应用集群下的定时任务处理方案(mysql)
  • 原文地址:https://www.cnblogs.com/hellolong/p/2771437.html
Copyright © 2020-2023  润新知