web页面缓存技术之Local Storage
业务:检测页面文本框的值是否有改变,有的话存入缓存,并存储到数据库,这样用户异常操作后再用浏览器打开网页,就可避免重新填写数据
数据库表:Test,包含字段:PageName,PageValue
BLL层代码:
#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代码:
/// <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:
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)代码:
@{
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>
一下午的成果,当然这样网络消耗很大,后面又给我说了下需求,点击提交按钮才把页面数据存入到缓存,不过改一下就好了。
web页面缓存技术之Local Storage的更多相关文章
- 比较全的.NET页面缓存技术文章
原文发布时间为:2009-11-04 -- 来源于本人的百度文章 [由搬家工具导入] http://www.cnblogs.com/jacksonwj/archive/2009/07/09/15197 ...
- 详细讲解PHP中缓存技术的应用
PHP,一门最近几年兴起的web设计脚本语言,由于它的强大和可伸缩性,近几年来得到长足的发展,php相比传统的asp网站,在速度上有绝对的优势,想mssql转6万条数据php如需要40秒,asp不下2 ...
- java缓存技术的介绍
一.什么是缓存1.Cache是高速缓冲存储器 一种特殊的存储器子系统,其中复制了频繁使用的数据以利于快速访问2.凡是位于速度相差较大的两种硬件/软件之间的,用于协调两者数据传输速度差异的结构,均可称之 ...
- .Net页面缓存OutPutCachexian详解
一 它在Web.Config中的位置 <system.web> <!--页面缓存--> <caching> <outputCacheSettings> ...
- .Net页面缓存OutPutCache详解
一 它在Web.Config中的位置 <system.web> <!--页面缓存--> <caching> <outputCacheSettings> ...
- Drupal启动阶段之二:页面缓存
页面缓存是什么意思?有些页面浏览量非常大,而且与状态无关,这类页面就可以使用页面缓存技术.在页面第一次请求完毕以后,将响应结果保存起来.下一次再请求同一页面时,就不需要从头到尾再执行一遍,只需要将第一 ...
- [转载]WEB缓存技术概述
[原文地址]http://www.hbjjrb.com/Jishu/ASP/201110/319372.html 引言 WWW是互联网上最受欢迎的应用之一,其快速增长造成网络拥塞和服务器超载,导致客户 ...
- ASP.NE的缓存技术提高Web站点的性能
一:我们为什么要使用缓存? 先来理解一下asp.net缓存技术的基本原理:把访问频繁的数据以及需要花大量的时间来加载的数据缓存在内存中,那么用户在下次请求同样的数据时,直接将内存中的数据返回给用户,从 ...
- Web项目开发中用到的缓存技术
在WEB开发中用来应付高流量最有效的办法就是用缓存技术,能有效的提高服务器负载性能,用空间换取时间.缓存一般用来 存储频繁访问的数据 临时存储耗时的计算结果 内存缓存减少磁盘IO 使用缓存的2个主要原 ...
随机推荐
- 多核CPU利用测试
一直在想程序上是否特意让线程在指定的CPU上去运行,这样可以提高运行效率,所以特地写个代码让CPU使用率画正弦曲线的实验,我使用的是AMD X4 641的CPU,为四核四线程的片子. 代码如下 # ...
- MySQL索引及Explain及常见优化
MySQL索引设计的原则 1. 搜索的索引列,不一定是所要选择的列.换句话说,最适合索引的列是出现在WHERE 子句中的列,或连接子句中指定的列,而不是出现在SELECT 关键字后的选择列表中的列. ...
- 各种开源协议介绍 BSD、Apache Licence、GPL V2 、GPL V3 、LGPL、MIT
现今存在的开源协议很多,而经过Open Source Initiative组织通过批准的开源协议目前有58种(http://www.opensource.org/licenses /alphabeti ...
- 如何用angularjs制作一个完整的表格之四__自定义ng-model标签的属性使其支持input之外的html元素
有的时候我们需要为非input类型的元素添加ng-model来实现双向的数据绑定,从而减少冗余代码,那么可以尝试一下的方式 例如:我页面中使用了contenteditable这个属性来实现用户可直接编 ...
- 一元云购完整源码 云购CMS系统 带安卓和ios手机客户端
看起来不错的一套一元云购CMS源码,源码包里面带了安卓和ios手机客户端,手机客户端需要自己反编译. 这里不做功能和其它更多的介绍,可以自己下载后慢慢测试了解. 下面演示图为亲测截图< ...
- centos git 升级应用
在阿里云服务器上部署Git 升级centos 自带的Git yum库自带版本为git1.7.1-3.el6_4.1. -------------------升级-------------------- ...
- 使用Ajax.ActionLink时,点击对应的按钮会重新加载一个页面,而不是在当前页面的指定模块加载
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- 钟表维修管理系统技术解析(一) MVC架构搭建
钟表维修管理系统技术解析(一) MVC架构搭建 1.1新建项目 第一步:打开VS2010界面,点击左上角文件,点击新建,选择项目 1.1(图1) 第二步:点击网站Web类型,选择ASP.net MV ...
- Solr4.8.0源码分析(17)之SolrCloud索引深入(4)
Solr4.8.0源码分析(17)之SolrCloud索引深入(4) 前面几节以add为例已经介绍了solrcloud索引链建索引的三步过程,delete以及deletebyquery跟add过程大同 ...
- PF_NETLINK应用实例NETLINK_KOBJECT_UEVENT具体实现--udev实现原理
PF_NETLINK应用实例NETLINK_KOBJECT_UEVENT具体实现--udev实现原理 相对于linux来说,udev还是一个新事物.然而,尽管它03年才出现,尽管它很低调(J),但它无 ...