web頁面緩存技術之Local Storage

業務:檢測頁面文本框的值是否有改變,有的話存入緩存,並存儲到數據庫,這樣用戶異常操做後再用瀏覽器打開網頁,就可避免從新填寫數據javascript

數據庫表:Test,包含字段:PageName,PageValuehtml


BLL層代碼:java

 

        #region 獲取緩存
        /// <summary>
        /// 獲取緩存
        /// </summary>
        /// <param name="pageName">頁面名稱</param>
        /// <returns></returns>
        public string GetCache(string pageName)
        {            
            if (string.IsNullOrEmpty(pageName)) throw new Exception("pageName is null");
            string selectPageValue_sql = "select PageValue from Test where PageName=@PageName";
            DataRowCollection rows = SqlHelper.ExecuteTable(selectPageValue_sql, new SqlParameter("@PageName", pageName)).Rows;
            if (rows.Count == 0) return string.Empty;
            return rows[0][0].ToString();
        } 
        #endregion
        
        #region 添加/修改頁面緩存

        /// <summary>
        /// 添加/修改頁面緩存
        /// </summary>        
        /// <param name="pageName">頁面名稱</param>
        /// <param name="pageValue">頁面值</param>        
        public void TestAE(string pageName, string pageValue)
        {
            if (string.IsNullOrEmpty(pageName)) throw new Exception("pageName is null");
            if (string.IsNullOrEmpty(pageValue)) throw new Exception("pageValue is null");
            string selectTest_sql = "select count(1) from Test where PageName=@PageName";
            bool isHasThisPageName = (Int32)SqlHelper.ExecuteScalar(selectTest_sql, new SqlParameter("@PageName", pageName)) == 1;
            if (isHasThisPageName)//修改
            {
                string updateTest_sql = "update Test set PageValue=@PageValue where PageName=@PageName";
                SqlHelper.ExecuteNonQuery(updateTest_sql,
                    new SqlParameter("@PageValue", pageValue),
                    new SqlParameter("@PageName", pageName));
            }
            else//添加
            {
                string addTest_sql = "insert into Test (PageName,PageValue) values (@PageName,@PageValue)";
                SqlHelper.ExecuteNonQuery(addTest_sql,
                    new SqlParameter("@PageName", pageName),
                    new SqlParameter("@PageValue", pageValue));
            }
        }

        #endregion

Controller代碼:jquery

 

 

        /// <summary>
        /// 實例化頁面緩存業務邏輯
        /// </summary>
        public static BLL.BLL_Test b_BLL_Test = new BLL.BLL_Test();
        /// <summary>
        /// 本地緩存結合網絡緩存
        /// </summary>
        /// <returns></returns>
        public ActionResult LocalCache()
        {
            return View();
        }
     /// <summary>
     /// 獲取頁面緩存
     /// </summary>
     /// <returns></returns>
     public JsonResult GetPageCache()
     {
       try
       {
           string pageName = Request["PageName"].ToLower();
          return Json(b_BLL_Test.GetCache(pageName),"json");
       }
       catch (Exception ex)
       {
          return Json("錯誤:" + ex.Message);
       }
     }
        /// <summary>
        /// 建立/更新頁面緩存
        /// </summary>
        /// <returns></returns>
        public ActionResult SetPageCache()
        {
            try
            {
                string pageName = Request["PageName"].ToLower();
                string pageValue = Request["PageValue"];
                b_BLL_Test.TestAE(pageName, pageValue);
                return Content(string.Empty);
            }
            catch (Exception ex)
            {
                return Content("錯誤:" + ex.Message);
            }
        }


localstoragehelper.js:sql

 

 

function CheckIsSupport_LocalStorage() {
    if (!window.localStorage) {
        alert("當前瀏覽器暫不支持Local Storage");
        return false;
    }
    return true;
}
function GetAlong_LocalStorage(key) {
    if (!CheckIsSupport_LocalStorage()) return;
    return window.localStorage.getItem(key);
}
function GetList_LocalStorage() {
    if (!CheckIsSupport_LocalStorage()) return;
    var storage = window.localStorage,
        list = [];
    for (var i = 0; i < storage.length; i++)
        list.push("{0}~{1}".format(storage.key(i), storage.getItem(storage.key(i))));
    return list;
}
function CreateOrSet_LocalStorage(key, value) {
    if (!CheckIsSupport_LocalStorage()) return;
    var storage = window.localStorage;
    if (storage.getItem(key)) storage.removeItem(key);
    storage.setItem(key, value);
}
function Remove_LocalStorage(key) {
    if (!CheckIsSupport_LocalStorage()) return;
    window.localStorage.removeItem(key);
}


localcache.js:數據庫

 

var pageName = window.location.pathname.toLowerCase(),        //頁面緩存名稱
           pageDateName = "{0}_date".format(pageName),        //頁面緩存建立時間名稱
           pageCache = GetAlong_LocalStorage(pageName),       //頁面本地緩存數據
           cache_date = GetAlong_LocalStorage(pageDateName);  //頁面本地緩存的建立時間
$(function () {
    //兼容性檢測
    if (!window.localStorage) {
        alert("當前瀏覽器不支持Local Storage本地存儲");
        return;
    }

    if (!CheckStringIsNull(pageCache)) {//頁面本地緩存存在
        if (!CheckStringIsNull(cache_date)) {//存在頁面本地緩存的建立時間
            if (ComputeDateMin(cache_date) >= 10) {//頁面本地緩存建立時間超過10分鐘
                GetPageNetCacheAndSet(pageName);
            } else {//頁面本地緩存建立時間未10分鐘
                GetPageLocalCache(pageCache);
            }
        } else {//頁面本地緩存建立時間不存在
            GetPageNetCacheAndSet(pageName);
        }
    } else {//頁面本地緩存不存在
        GetPageNetCacheAndSet(pageName);
    }

    //文本框只要一改變存入緩存(存入本地和網絡)
    $("input[type=text]").on("change", function () {
        var pageValue = [];
        $("input[type=text]").each(function (index, item) {
            var id = $(item).attr("id"),
                val = CheckStringIsNull($(item).val()) ? "" : $(item).val();            
            pageValue[index] = { "InputID": id, "InputValue": val };
        });
        if (CheckStringIsNull(pageValue)) return;
        //先更新本地緩存,不管網絡緩存是否更新成功
        CreateOrSet_LocalStorage(pageName, JSON.stringify(pageValue));
        CreateOrSet_LocalStorage(pageDateName, new Date().getTime());
        $.post("/Home/SetPageCache", { PageName: pageName, PageValue: JSON.stringify(pageValue) }, function (json) {
            if (!CheckStringIsNull(json)) {//更新時出錯
                alert(json);
                return;
            }
        }, "text");
    });

});

//檢測字符串是否爲空
function CheckStringIsNull(str) {
    return (str == "" || str == null || typeof (str) == undefined);
}
//計算相差分鐘數
function ComputeDateMin(date) {
    var minutes = Math.floor((((new Date().getTime() - date) % (24 * 3600 * 1000)) % (3600 * 1000)) / (60 * 1000));
}

//獲取頁面網絡緩存並將緩存數據賦值到頁面,同時更新頁面緩存建立時間
function GetPageNetCacheAndSet() {
    $.post("/Home/GetPageCache", { PageName: pageName }, function (json) {
        if (json.indexOf("錯誤") == -1) {
            if (!CheckStringIsNull(json)) {
                var cache_list = eval('(' + json + ')');
                $(cache_list).each(function (index, item) {                 
                    $("#{0}".format(cache_list[index].InputID))
                        .val(cache_list[index].InputValue);
                });
                CreateOrSet_LocalStorage(pageName, json);
                CreateOrSet_LocalStorage(pageDateName, new Date().getTime());//更新緩存建立時間
            }
        } else {//獲取網絡緩存時出錯
            alert(json);
        }
    }, "json");
}

//獲取頁面本地緩存並將緩存數據賦值到頁面,同時更新頁面緩存建立時間
function GetPageLocalCache(pageCache) {
    if (CheckStringIsNull(pageCache)) {//本地爲空,此處爲多餘判斷
        GetPageNetCacheAndSet();
    }
    var cache_list = eval('(' + pageCache + ')');
    $(cache_list).each(function (index, item) {        
        $("#{0}".format(cache_list[index].InputID))
            .val(cache_list[index].InputValue);
    });
    CreateOrSet_LocalStorage(pageDateName, new Date().getTime());//更新緩存建立時間
}


 

 

頁面(mvc4)代碼:json

 

 

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>LocalCache</title>
    <script src="~/Content/js/comm/jquery.js"></script>
    <script src="~/Content/js/comm/comm.js?@DateTime.Now.Millisecond"></script>
    <script src="~/Content/js/comm/localstoragehelper.js?@DateTime.Now.Millisecond"></script>
    <script src="~/Content/js/home/localcache.js?@DateTime.Now.Millisecond"></script>
</head>
<body>
    <!-- http://www.cnblogs.com/xiaowei0705/archive/2011/04/19/2021372.html -->    
    <input id="key1" type="text" placeholder="enter key name..." />
    <input id="key2" type="text" placeholder="enter key name..." />
    <input id="key3" type="text" placeholder="enter key name..." />
    <input id="key4" type="text" placeholder="enter key name..." />
    <input id="key5" type="text" placeholder="enter key name..." />
    <input id="key6" type="text" placeholder="enter key name..." />
    <input id="key7" type="text" placeholder="enter key name..." />
    <div>
        @*<br /><br />
            <!-- list -->
            <input id="list" type="button" value="get list" autofocus /><br /><br />

            <!-- create or set -->
            <input id="key" type="text" placeholder="enter key name..." />
            <input id="value" type="text" placeholder="enter key value..." />
            <input id="createorset" type="button" value="create or set" /><br /><br />

            <!-- remove -->
            <input id="removekey" type="text" placeholder="enter will to remove key name..." />
            <input id="remove" type="button" value="remove" />*@
        @*<script>
                $(function () {
                    $("input[type=button]").on("click", function () {
                        var id = $(this).attr("id");
                        switch (id) {
                            case "list":
                                var list = GetList_LocalStorage(),
                                    $con = $("#content");
                                if (list == "" || list == null || typeof (list) == undefined) {
                                    $con.text("has no local storage.");
                                    return;
                                }
                                $con.empty().append("Local storage List:<br/>");
                                for (var i = 0; i < list.length; i++) {
                                    $con.append("key:{0}  value:{1}<hr/>"
                                        .format(list[i].split("~")[0], list[i].split("~")[1]));
                                }
                                break;
                            case "createorset":
                                CreateOrSet_LocalStorage($("#key").val(), $("#value").val());
                                $("#list").click();
                                break;
                            case "remove":
                                Remove_LocalStorage($("#removekey").val());
                                $("#list").click();
                                break;
                            default:

                        }
                    });
                });
            </script>*@
    </div>
</body>
</html>


一下午的成果,固然這樣網絡消耗很大,後面又給我說了下需求,點擊提交按鈕才把頁面數據存入到緩存,不過改一下就行了。瀏覽器