学习笔记 --- 缓存、动态页面静态化、网站优化

一、缓存

缓存(Cache)技术在软件开发过程中有着广泛的用途, 它对提升软件性能和改善客户体验有很大帮助. 所谓缓存, 是指将那些经常重复的操作结果暂时存放起来, 在以后的执行过程中, 只要使用前面的暂存结果即可. 缓存技术在日常生活中随处可见, 就拿排队买票来说吧: 买票时需要先排队, 等轮到自己了, 再告诉售票员你需要买那里的票, 售票员查询完后告诉你有还是没有. 若有, 付款走人; 若没有, 离开队列. 例如, 北京到上海是热门线路, 票很快就卖完了, 但是根据购票的规则, 仍然有许多乘客会先排队, 然后问有没有北京到上海的票, 结果只能默默离开队列. 如果每个人都问一遍的话, 售票员估计得烦死. 于是, 售票员在窗口上挂个牌子, 写上”北京到上海(无票)”, 之后再要购买该票的乘客看到这个牌子就不会在队列中继续等待了. 这就是生活中的一个缓存事例.


由此可见, 缓存的思想就是: 尽量减少执行那些费时的、需要经常重复执行的工作的次数. 在计算机的世界中, 执行速度最慢的操作就是IO操作, 也就是读写硬盘的操作. 因此, 构建一个高效的桌面应用程序或网站应用程序时, 很重要的一个因素就是尽可能少的减少IO操作. 比如, 相同的数据没有必要每次都从数据库中读取, 在第一次读取出来后缓存起来即可, 第二次就不需要在做IO操作了.


那么在我们开发Web网站的过程中, 到底有多少工作可以采用用缓存呢? 或者说, 我们可以在哪些地方使用缓存呢? 见下图: 下图是客户端浏览器和Web服务器之间的一次完整的通信过程, 红色圆圈标示了可以采用缓存的地方.

关于上图, 如果一边描述请求过程, 一边描述缓存可能会不便理解. 像做手术一样, 这里首先弄清楚整个请求过程, 然后从整体上对关键节点设置的缓存进行描述.


上图所示的请求过程:

客户端浏览器首先发送HttpRequest请求到IIS服务器, 当然也有一些企业内部网络或者小型机关网络中会设置代理服务器. 代理服务器在请求过程中可以看作是一个转发请求的中继器, 或者干脆在这里忽略代理服务器也行.

IIS服务器接受到请求后, 会根据请求地址进行判断, 例如: *.html、*.jpg等静态内容的资源, 会直接由IIS寻找资源并返回给客户端浏览器; 例如: *.aspx、*.ashx、*.asmx等asp.net中的动态内容会交给aspnet_isapi.dll处理.

aspnet_isapi.dll将请求转交给asp.net组件处理, 这时asp.net组件会启动一个asp.net的进程(进程名称为w3wp.exe), 该进程会创建一个应用程序域(一个进程可以创建多个应用程序域, 一个应用程序域中可以跑多个线程), 在应用程序域中会创建asp.net执行环境HttpRuntime, 在asp.net执行环境中创建HttpContext对象并启动HttpApplication应用程序管道(HttpRuntime中可以同时创建多个HttpContext和HttpApplication, 也就是说在HttpRuntime中可以同时进行多套处理流程). 其中, HttpContext其实就是对一堆参数的封装, 如: HttpRequest、HttpResponse、HttpServerUtility等, HttpContext可以在整个HttpApplication管道中使用, 可以取出其中的参数, 并且HttpContext本身也可以当作一个字典来使用. HttpApplication也就是asp.net应用程序管道或者叫asp.net应用程序生命周期, 它是实际处理客户端请求的地方, 我们只能通过Global.asax或者IHttpModule接口来人为控制客户端请求的处理过程.


在HttpApplication启动后, 在IIS6.0中会有17个事件(IIS7.0中会更多), 其中包括: 用户验证、用户授权等等, 这些事件中有两个重要的时间点, 第一个时间点是在第7个事件之后, 也就是PostResolveRequestCache事件之后, 映射请求的处理程序(需查找配置文件); 第二个时间点是在第11个事件之后, 也就是PreRequestHandlerExecute事件之后, 执行处理程序, 像对*.aspx的处理程序System.Web.UI.PageHandlerFactory.Page就是实现了IHttpHandler接口的类. 在这个时间点中执行处理程序并进入页面的生命周期, 其中最重要的是页面处理的11个事件(如: Page_Int、Page_Load、Page_PreRender、Page_SaveState、Page_Unload), 我们在这11个事件中, 完成读取aspx页面模板、控件预读、读取视图状态、控件属性赋值等工作, 并且要求我们程序员调用BLL、DAL、DE以及数据库等完成业务逻辑的处理工作. 最后, 在由页面对象中的Render方法将结果发送给客户端浏览器, 客户端浏览器再呈现给用户.

至此, 完成了一次完整的请求过程. 那么, 我们的缓存工作应该在哪里做呢?


缓存该在哪里做, 取决于我们能在整个请求过程的什么位置动手. 我们依然从客户端浏览器开始:

首先, 最好的情况是客户端不发送任何请求直接就能获得数据, 这种情况下, 用于缓存的数据保存在客户端浏览器的缓存中.


其次, 在具有代理服务器的网络环境中, 代理服务器可以针对那些经常访问的网页制作缓存, 当局域网中第一台主机请求了某个网页并返回结果后, 局域网中的第二台主机再请求同一个网页, 这时代理服务器会直接返回上一次缓存的结果, 并不会向网络中的IIS服务器发送请求, 例如: 现在的连接电信和网通线路的加速器等. 但是代理服务器通常有自己专门的管理软件和管理系统, 作为网站开发人员对代理服务器的控制能力有限.


再次, 前面也说过, 当用户将请求地址发送到IIS服务器时, IIS服务器会根据请求地址选择不同的行为, 如: 对于*.aspx页面会走应用程序管道, 而对*.html、*.jpg等资源会直接返回资源, 那么我们可以把那些频繁访问的页面做成*.html文件, 这样用户请求*.html, 将不用再走应用程序管道, 因此会提升效率. 例如: 网站首页、或某些突发新闻或突发事件等, 可以考虑做成静态网页. 就拿”天气预报的发布页面”打比方: 天气预报的发布页面的访问用户非常多, 我们可以考虑将发布页做成静态的*.html网页, 之后在整个网站程序启动时, 在Gboabl.asax的Application_Start事件处理器中, 创建子线程以实现每3个小时重新获取数据生成新的天气发布页面内容.


之后的asp.net的处理流程, 作为程序员我们是无法干涉的. 直到启动HttpApplication管道后, 我们才可以通过Global.asax或IHttpModule来控制请求处理过程, 在应用程序管道中适合做整页或用户控件的缓存. 如: 缓存热门页面, 我们可以自动缓存整个网站中访问量超过一定数值(阀值)的页面, 其中为了减小IO操作, 将缓存的页面放在内容中.


最后, 我们程序员可以操作的地方就是页面处理管道或者称为页面生命周期, 我们可以页面对象的11个事件中, 采用数据缓存的方式减小访问数据库的次数, 也就是减少IO操作. 还有些真假分页等问题涉及网站的优化, 稍后再讨论.


总之, 我们可以采用缓存的地方有以下5处:

1. 客户端浏览器的缓存(非Cookie, Cookie只能放字符串信息)

2. 如果有代理服务器的话, 可以在代理服务器中缓存整个网页(本篇仅讨论网站开发的相关内容)

3. 将频繁访问的资源做成*.html等的静态内容, (我们可以将静态资源缓存在ramdisk等开辟的内存盘中,  以进一步减少对硬盘的访问).

4. 在应用程序处理管道或应用程序生命周期中, 进行整页缓存或用户控件的局部缓存

5. 在页面处理管道或页面生命周期中, 做数据缓存


下面我们来详细论述这些缓存手段:

1. 客户端浏览器上的缓存(非Cookie, Cookie中的内容为: 键和值均为string类型的键值对)

我们可以通过在Http回应中增加特定的头部说明来指定浏览器的缓存策略; 添加头部说明的手段既可以通过页面指令声明设置, 也可以通过编程方式设置.


对于图片、Javascript脚本、CSS等资源, 可以在IIS管理器中, 右击图片等资源, 选择”属性” --> HttpHeaders后, 勾选Enable Content Expiration并设置时间即可. 一种值得推荐的手段是, 将需要缓存的资源分类, 如: image/dynamic/、image/static/, 这样我们可以再文件夹上, 选择属性中的HttpHeaders进行设置. 否则, 针对每一个静态资源设置HttpHeaders将是件非常痛苦的事情. 此外, 还可以采用一款名为CacheRight的工具可以提供缓存资源的统一配置.


查看或设置浏览器缓存位置:  IE --> Internet选项 --> 常规 --> 临时Internet文件 --> 设置

 

Html文件的Head中的缓存设置:

<meta http-equiv="pragma" content="no-cache" />

<meta http-equiv="Cache-Control" content="no-cache" />

<meta http-equiv="expires" content="Wed, 26 Feb 1997 08:21:57 GMT" />

浏览器中关于Cache的3属性:

Cache-Control:

设置相对过期时间, max-age指明以秒为单位的缓存时间. 若对静态资源只缓存一次, 可以设置max-age的值为315360000000 (一万年).

Http协议的cache-control的常见取值及其组合释义:

no-cache: 数据内容不能被缓存, 每次请求都重新访问服务器, 若有max-age, 则缓存期间不访问服务器.

no-store: 不仅不能缓存, 连暂存也不可以(即: 临时文件夹中不能暂存该资源)

private(默认): 只能在浏览器中缓存, 只有在第一次请求的时候才访问服务器, 若有max-age, 则缓存期间不访问服务器.

public: 可以被任何缓存区缓存, 如: 浏览器、服务器、代理服务器等

max-age: 相对过期时间, 即以秒为单位的缓存时间.

no-cache, private: 打开新窗口时候重新访问服务器, 若设置max-age, 则缓存期间不访问服务器.

private, 正数的max-age: 后退时候不会访问服务器

no-cache, 正数的max-age: 后退时会访问服务器

点击刷新: 无论如何都会访问服务器.

Expires:

设置以分钟为单位的绝对过期时间, 优先级比Cache-Control低, 同时设置Expires和Cache-Control则后者生效.

Last-Modified:

该资源的最后修改时间, 在浏览器下一次请求资源时, 浏览器将先发送一个请求到服务器上, 并附上If-Unmodified-Since头来说明浏览器所缓存资源的最后修改时间, 如果服务器发现没有修改, 则直接返回304(Not Modified)回应信息给浏览器(内容很少), 如果服务器对比时间发现修改了, 则照常返回所请求的资源.


注意:

Last-Modified属性通常和Expires或Cache-Control属性配合使用, 因为即使浏览器设置缓存, 当用户点击”刷新”按钮时, 浏览器会忽略缓存继续向服务器发送请求, 这时Last-Modified将能够很好的减小回应开销.


ETag将返回给浏览器一个资源ID, 如果有了新版本则正常发送并附上新ID, 否则返回304, 但是在服务器集群情况下, 每个服务器将返回不同的ID, 因此不建议使用ETag.


以上描述的客户端浏览器缓存是指存储位置在客户端浏览器, 但是对客户端浏览器缓存的实际设置工作是在服务器上的资源中完成的. 虽然刚才我们介绍了有关于客户端浏览器缓存的属性, 但是实际上对这些属性的设置工作都需要在服务器的资源中做设置. 我们有两种操作手段对浏览器缓存进行设置, 一个是通过页面指令声明来设置, 另外一个是通过编程方式来设置.


浏览器缓存的设置手段:

第一: 通过页面指令声明来设置HTTP的缓存

页面指令<%@ OutputCache Location=”Any” Duration=”10” VaryByParam=”ProductId” VaryByHeader=”Accept-Language”%>中的Location用来设置缓存的位置, 该属性常见的值为:

Any(默认): 输出缓存可以位于任何地点, 对应于HttpCacheability.Public. 如: 客户端浏览器、代理服务器或服务器本身.

Client: 只能位于发出请求的客户端浏览器, 对应于HttpCacheability.Private.

Downstream: 输出缓存可以位于除服务器本身的其他任何地方, 如: 客户端浏览器、代理服务器.

Server: 输出缓存位于Web服务器本身, 对应于HttpCacheability.Server

ServerAndClient: 输出缓存只能位于服务器本身或客户端浏览器, 对应于HttpCacheability.Private和HttpCacheability.Server

None: 禁用输出缓存, 对应于HttpCacheability.NoCache.

VaryByParam属性: 根据请求参数的不同而缓存不同的版本. 多个值用分号(;)分隔, *号表示为任意参数或参数组合缓存不同版本, “none”表示只缓存一个版本.

VaryByHeader属性: 根据请求头来缓存不同的版本, 如同一页面的不同语言版本.

VaryByCustom属性: 根据自定义参数来缓存不同的版本, 如: VaryByCunstom=”browser”是系统已实现的, 根据浏览器名称和版本号缓存不同的版本. 也可以, 根据自定义参数来缓存, 如: VaryByCustom=”happy”, 此时系统不知道如何解释happy, 因此需要在Global.asax或IHttpModule实现类中重写GetVaryByCustomString()方法, 来完成处理逻辑.

VaryByControl属性: 根据用户控件中的服务器控件ID来缓存不同版本.

更高级的方式, 是通过配置文件来设置HTTP的缓存.

页面指令为<%@ OutputCache CacheProfile=”cacheconfig”%>, 其中cacheconfig是配置文件中的缓存配置节中CacheProfile的名称.

ContractedBlock.gif ExpandedBlockStart.gif View Code
< system.web >
< caching >
< outputCacheSettings >
< outputCacheProfiles >
< add name ="cacheconfig" duration ="10" varyByParam ="none" />
</ outputCacheProfiles >
</ outputCacheSettings >
</ caching >
</ system.web >

第二: 通过编程方式设置HTTP的缓存特性

在页面后台文件*.cs文件或*.ashx等其他代码文件中, 我们可以通过HttpResponse类的实例对象上的Cache属性or页面对象的Response属性上的Cache属性来设定缓存特性.

VaryByHeaders[“Accept-Language”] = true: 设置缓存同一页的不同语言版本

SetMaxAge(): 设置活动过期时间

SetExpires()方法: 设置绝对过期时间

SetLastModified(): 设置最后修改时间

SetNoStore(): 设置不要缓存

SetNoServerCaching(): 关闭服务器缓存

SetCacheability(): 设置缓存位置, 其参数类型为HttpCacheability枚举类型, 可选项如下:

  NoCache: 将会在Http响应头添加Cache-Control: no-cache标头, 表示禁用缓存.

  Private: 只在客户端浏览器缓存(关闭代理服务器缓存).

  Public: 可在任意位置缓存.

  Server: 只能在服务器上缓存.

  ServerAndNoCache: 只能在服务器上缓存, 其余都不能缓存, 将会在Http响应头添加Cache-Control: no-cache标头.

  ServerAndPrivate: 只能在服务器和客户端浏览器缓存, 不能再代理服务器上缓存.


注意:

其中, 设置NoCache和ServerAndNoCache, 将会在Http响应头中添加如下内容:

        Cache-Control: no-cache

              Pragma: no-cache

              Expires: -1

以上设置可防止浏览器在自己的历史记录文件夹中缓存该页, 前进和后退按钮都会请求响应新的版本.


SetAllowResponseInBrowserHistory()方法: 允许在浏览器历史记录中响应, 若参数为true, 则可覆盖HttpCacheability的设置, 但如果SetCacheability设置为NoCache或ServerAndNoCache, 则会忽略SetAlloewResponseInBrowerHistory的值.


Cookies和代理缓存不能结合的很好, 当使用cookie时,不要允许代理缓存。设置Location为Private、Server或ServerAndPrivate。


用户控件中的缓存(部分页缓存)不可以使用Location属性, 因为在不同页面中, 同一用户控件缓存的结果将会有多个. 如果希望用户控件缓存同一结果, 可以添加Shared=”true”属性来实现.


页面缓存和用户控件缓存的Duration属性的时间长短问题: 结论是按照时间长的来算. 如: 页面缓存长, 用户控件缓存短, 则用户控件的缓存内容会和页面缓存一起到期; 若用户控件缓存长, 页面缓存短, 则用户控件的缓存内容会一直到用户控件的缓存时间结束.


Http Referer是Request.Header的一部分, 他可以指出是从哪个页面链接过来的, 但是可以伪造. 我们可以通过this.Request.Headers[“Referer”]或this.Request.UrlReferrer获得其内容, 最好通过this.Request.UrlReferrer.OriginalString来避轨编码不一致的问题.


2. 和代理服务器相关的缓存措施

对我们程序员来说, 和代理服务器相关的操作无非也是在服务器上设置的, 参见: 1中的浏览器缓存设置中的操作手段.


3. 将频繁访问的资源做成*.html等的静态内容

像天气预报这样的即时性要求不是很强的页面, 非常适合做成静态的html页面. 我们可以在网站的Global.asax中, 每3个小时重新读取一下数据, 将读取的数据生成新的html页面并覆盖掉老页面. 网站首页也是访问极其频繁的, 做法类似, 只是时间短点. 为简便起见, 直接用txt文件模拟数据库.

//App_Data/WeatherData.txt, 内容随便.

// WeatherReport/Today.html

ContractedBlock.gif ExpandedBlockStart.gif View Code
< html >< head >< title ></ title ></ head >< body >< h1 > 今日天气情况: </ h1 >< hr />< ul >< li id ='time' ></ li >< li > 拉拉啦, 哇哈哈 </ li ></ ul >< script type ='text/javascript' > var time = document.getElementById( ' time ' );time.innerText = getCurrentTime(); function getCurrentTime(){ var date = new Date(); var year = date.getFullYear(); var month = date.getMonth() + 1 ; var day = date.getDate(); var hh = date.getHours(); var mm = date.getMinutes(); var ss = date.getSeconds(); var now = year + ' - ' + month + ' - ' + day + ' ' + hh + ' : ' + mm + ' : ' + ss; return now;} </ script ></ body ></ html >

注意: Global.asax是继承自HttpApplication类的子类, 如果网站存在Global.asax, 它会在HttpRuntime运行环境创建HttpApplication类的对象时, 用Global类的对象替带HttpApplication类的对象, 并且Application_Start、Application_End事件激发只会在服务器启动时进行, 而Application_BeginRequest等事件处理器则每次请求时都会激发. 本例在Application_Start中为保证主线程不被过分占用, 采用子线程创建timer并更新天气信息.

//Global.asax

ContractedBlock.gif ExpandedBlockStart.gif View Code
<% @ Application Language = " C# " %>

< script runat = " server " >

static readonly string datapath = AppDomain.CurrentDomain.BaseDirectory + " /App_Data/WeatherData.txt " ;
static readonly string weatherhtml = AppDomain.CurrentDomain.BaseDirectory + " /WeatherReport/Today.htm " ;
static System.Timers.Timer timer;
void Application_Start( object sender, EventArgs e)
{
// Code that runs on application startup
System.Threading.Thread thread = new System.Threading.Thread( new System.Threading.ThreadStart(doSth));
thread.Start();
}

private static void doSth()
{
timer
= new System.Timers.Timer( 180000 );
timer.Elapsed
+= new System.Timers.ElapsedEventHandler(timer_Elapsed);
timer.Start();
}

static void timer_Elapsed( object sender, System.Timers.ElapsedEventArgs e)
{
timer.Stop();
string weather = string .Empty;
using (System.IO.StreamReader sr = new System.IO.StreamReader(datapath, Encoding.UTF8))
{
weather
= sr.ReadToEnd();
}
string weathcontent = createHtml(weather);
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(weatherhtml, false , Encoding.UTF8))
{
sw.Write(weathcontent);
sw.Flush();
}
timer.Start();
}

private static string createHtml( string weather)
{
return " <html><head><title></title></head><body><h1>今日天气情况: </h1><hr /><ul><li id='time'></li><li> " + weather + " </li></ul><script type='text/javascript'>var time = document.getElementById('time');time.innerText = getCurrentTime();function getCurrentTime(){var date = new Date();var year = date.getFullYear();var month = date.getMonth() + 1;var day = date.getDate();var hh = date.getHours();var mm = date.getMinutes();var ss = date.getSeconds();var now = year + '-' + month + '-' + day + ' ' + hh + ':' + mm + ':' + ss;return now;}</ " + " script></body></html> " ;
}

void Application_End( object sender, EventArgs e)
{
// Code that runs on application shutdown

}

void Application_Error( object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs

}

void Session_Start( object sender, EventArgs e)
{
// Code that runs when a new session is started

}

void Session_End( object sender, EventArgs e)
{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.

}

</ script >

4. 通过Global.asax或IHttpModule在应用程序处理管道中做整页缓存或用户控件局部缓存

第3所述的情况, 可以认为是在IIS级别的缓存, 它的目的是避免或劲量少走应用程序处理流程. 但是这种IIS级别的缓存只适合那些很少的热门资源, 如果所有页面都做成静态页面就又回到了古老的纯html时代, 当然是得不偿失. 那么大部分的资源还需要是动态的, 也就是说必须要走应用程序处理流程, 程序员可以通过Global.asax和IHttpModule来人为的影响应用程序处理管道. 因此, 在HttpApplication级的缓存是正是通过Global.asax或IHttpModule来完成的.


“动态页面静态化”:

在文章的标题中, 提到过一种称为”动态页面静态化”的技术, 暂且不管这个称谓是否贴切(园子有议论这个的帖子). 无论名称是什么, 我觉得那只是个称谓而已, 关键的是它用来解决什么问题. 早期的搜索引擎并不能很好的收录如*.aspx等的动态页面, 但是对*.html等静态页面收录良好, 于是乎产生了一种UrlRewrite(Url重写)的技术. 另外一种”动态页面静态化”的技术就和今天的缓存挂钩了, 那就是把用户对*.aspx页面的请求结果缓存到html文件中.


第一种: UrlRewrite技术:

它的原理是把用户发出的对静态页面(*.html)的请求转化映射为对动态页面(*.aspx)的请求. UrlRewrite技术主要就是用来解决当时搜索引擎收录的问题, 如今的各大搜索引擎中宣称已经不存在这个问题了. 那么这个技术现今就没用了吗? 在一篇讲Yahoo团队的34条网站优化手段的文章中, 看到一处用UrlWriter的地方, 说的是为了减小客户端浏览器在请求回应过程中传递的数据, 在网站真正实施发布时尽量采用”短名称”, 如: 超链接中用p.html代替product.html、在JS中用d代表window.document等. 这篇文章说短文件名有利于减少传输过程中的数据量, 但是客户体验较差, 这时就可以通过UrlRewrite技术来改善用户体验, 具体做法是在html代码中使用p.html做超链接, 用户请求时依然采用product.html, UrlRewrite的工作就是把请求中的product.html转换映射为p.html. 这和”把*.html映射到*.aspx”是一个道理. 再有一个和缓存相关的用处, 就是url中含有类似*.aspx?id=123的查询字符串时, 很多代理是不会缓存这种请求的, 这时我们可以通过UrlRewrite技术将*.aspx?id=123变成/123.aspx, 从而使代理服务器缓存这种请求.

示例: 静态*html映射到动态页面*.aspx, 因为默认对*.html文件的处理是由IIS来完成的, 因此这里必须在IIS中, Web程序的属性中, “主目录” ---> “应用程序设置” --> “配置”中分别添加*.htm和*.html到aspnet_isapi.dll的配置. 注意: “检查文件是否存在” 的勾一定要去掉, 这时对*.htm和*.html的处理将会交给asp.net处理.

// UrlRewriteDemo/App_Code/ HtmlToAspx.cs

ContractedBlock.gif ExpandedBlockStart.gif View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace HtmlAspxModel
{
/// <summary>
/// Summary description for HtmlToAspx
/// </summary>
public class HtmlToAspx : IHttpModule
{
#region IHttpModule Members

public void Dispose()
{
throw new NotImplementedException();
}

public void Init(HttpApplication application)
{
// 更通用的做法是采用IHttpModule来操作HttpApplication管道
// 注册事件
application.BeginRequest += new EventHandler(application_BeginRequest);
}

void application_BeginRequest( object sender, EventArgs e)
{
HttpApplication ha
= sender as HttpApplication;
HttpContext hc
= ha.Context;

string rawurl = ha.Context.Request.RawUrl;

if (rawurl.EndsWith( " .htm " ,StringComparison.OrdinalIgnoreCase)) // 判断以*.htm结尾
{
string regnoparam = @" /(\w+)\.htm " ; // 不含参数
string regparam = @" /(\w+)\=(\d+) " ; // 含参数
if (System.Text.RegularExpressions.Regex.Match(rawurl, regparam, System.Text.RegularExpressions.RegexOptions.IgnoreCase).Success) // 匹配成功
{
System.Text.RegularExpressions.MatchCollection mc
= System.Text.RegularExpressions.Regex.Matches(rawurl, regparam, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
rawurl
= rawurl.Replace( " .htm " , "" );
for ( int i = 0 ; i < mc.Count; i ++ )
{
if (i == 0 )
{
rawurl
= rawurl.Replace(mc[i].Value, " .aspx? " + mc[i].Value.Substring( 1 ,mc[i].Value.Length - 1 ));
}
else
{
rawurl
= rawurl.Replace(mc[i].Value, " & " + mc[i].Value.Substring( 1 , mc[i].Value.Length - 1 ));
}
}
}
else if (System.Text.RegularExpressions.Regex.Match(rawurl, regnoparam, System.Text.RegularExpressions.RegexOptions.IgnoreCase).Success)
{
rawurl
= rawurl.Replace( " .htm " , " .aspx " );
}
hc.RewritePath(rawurl);
}
}

#endregion
}
}

//UrlRewriteDemo/Default.aspx

ContractedBlock.gif ExpandedBlockStart.gif View Code
<% @ Page Language = " C# " AutoEventWireup = " true " CodeFile = " Default.aspx.cs " Inherits = " _Default " %>

<! 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 runat ="server" >
< title ></ title >
</ head >
< body >
< p ></ p >< a href ="WebFormNoParam.htm" > WebFormNoParam.htm </ a ></ p >< br />
< p ></ p >< a href ="WebFormWithParam/id=55/name=123.htm" > WebFormWithParam/id=55/name=123.htm </ a ></ p >< br />
< form id ="form" method ="post" action ="WebFormWithParam.htm" >
< div >
< label for ="id" > 编号: &nbsp; </ label >
< input type ="text" id ="id" name ="id" />< br />
< label for ="name" > 姓名: &nbsp; </ label >
< input type ="text" id ="name" name ="name" />< br />
< input type ="submit" value ="提交" />
</ div >
</ form >
</ body >
</ html >

//UrlRewriteDemo/WebFormNoParam.aspx

ContractedBlock.gif ExpandedBlockStart.gif View Code
<% @ Page Language = " C# " AutoEventWireup = " true " CodeFile = " WebFormNoParam.aspx.cs " Inherits = " WebFormNoParam " %>

<! 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 runat ="server" >
< title ></ title >
</ head >
< body >
< h1 > This is a aspx page! </ h1 >
</ body >
</ html >

//UrlRewriteDemo/WebFormWithParam.aspx

ContractedBlock.gif ExpandedBlockStart.gif View Code
<% @ Page Language = " C# " AutoEventWireup = " true " CodeFile = " WebFormWithParam.aspx.cs " Inherits = " WebFormWithParam " %>

<! 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 runat ="server" >
< title ></ title >
</ head >
< body >
< label for ="id" > 编号: &nbsp; </ label >
< input type ="text" id ="id" runat ="server" />< br />
< label for ="name" > 姓名: &nbsp; </ label >
< input type ="text" id ="name" runat ="server" />< br />
</ body >
</ html >

//UrlRewriteDemo/web.config

ContractedBlock.gif ExpandedBlockStart.gif View Code
<? xml version="1.0" ?>
<!--
Note: As an alternative to hand editing this file you can use the
web admin tool to configure settings for your application. Use
the Website->Asp.Net Configuration option in Visual Studio.
A full list of settings and comments can be found in
machine.config.comments usually located in
\Windows\Microsoft.Net\Framework\v2.x\Config
-->
< configuration >
< configSections >
< sectionGroup name ="system.web.extensions" type ="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" >
< sectionGroup name ="scripting" type ="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" >
< section name ="scriptResourceHandler" type ="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission ="false" allowDefinition ="MachineToApplication" />
< sectionGroup name ="webServices" type ="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" >
< section name ="jsonSerialization" type ="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission ="false" allowDefinition ="Everywhere" />
< section name ="profileService" type ="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission ="false" allowDefinition ="MachineToApplication" />
< section name ="authenticationService" type ="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission ="false" allowDefinition ="MachineToApplication" />
< section name ="roleService" type ="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission ="false" allowDefinition ="MachineToApplication" />
</ sectionGroup >
</ sectionGroup >
</ sectionGroup >
</ configSections >
< appSettings />
< connectionStrings />
< system.web >
<!--
Set compilation debug="true" to insert debugging
symbols into the compiled page. Because this
affects performance, set this value to true only
during development.
-->
< compilation debug ="true" >
< assemblies >
< add assembly ="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
< add assembly ="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
< add assembly ="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
< add assembly ="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
</ assemblies >
</ compilation >
<!--
The <authentication> section enables configuration
of the security authentication mode used by
ASP.NET to identify an incoming user.
-->
< authentication mode ="Windows" />
<!--
The <customErrors> section enables configuration
of what to do if/when an unhandled error occurs
during the execution of a request. Specifically,
it enables developers to configure html error pages
to be displayed in place of a error stack trace.

<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
-->
< pages >
< controls >
< add tagPrefix ="asp" namespace ="System.Web.UI" assembly ="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
< add tagPrefix ="asp" namespace ="System.Web.UI.WebControls" assembly ="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</ controls >
</ pages >
< httpHandlers >
< remove verb ="*" path ="*.asmx" />
< add verb ="*" path ="*.asmx" validate ="false" type ="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
< add verb ="*" path ="*_AppService.axd" validate ="false" type ="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
< add verb ="GET,HEAD" path ="ScriptResource.axd" type ="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate ="false" />
</ httpHandlers >
< httpModules >
< add name ="ScriptModule" type ="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
< add name ="HtmltoAspx" type ="HtmlAspxModel.HtmlToAspx" />
</ httpModules >
</ system.web >
< system.codedom >
< compilers >
< compiler language ="c#;cs;csharp" extension =".cs" warningLevel ="4" type ="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
< providerOption name ="CompilerVersion" value ="v3.5" />
< providerOption name ="WarnAsError" value ="false" />
</ compiler >
< compiler language ="vb;vbs;visualbasic;vbscript" extension =".vb" warningLevel ="4" type ="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
< providerOption name ="CompilerVersion" value ="v3.5" />
< providerOption name ="OptionInfer" value ="true" />
< providerOption name ="WarnAsError" value ="false" />
</ compiler >
</ compilers >
</ system.codedom >
<!--
The system.webServer section is required for running ASP.NET AJAX under Internet
Information Services 7.0. It is not necessary for previous version of IIS.
-->
< system.webServer >
< validation validateIntegratedModeConfiguration ="false" />
< modules >
< remove name ="ScriptModule" />
< add name ="ScriptModule" preCondition ="managedHandler" type ="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</ modules >
< handlers >
< remove name ="WebServiceHandlerFactory-Integrated" />
< remove name ="ScriptHandlerFactory" />
< remove name ="ScriptHandlerFactoryAppServices" />
< remove name ="ScriptResource" />
< add name ="ScriptHandlerFactory" verb ="*" path ="*.asmx" preCondition ="integratedMode" type ="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
< add name ="ScriptHandlerFactoryAppServices" verb ="*" path ="*_AppService.axd" preCondition ="integratedMode" type ="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
< add name ="ScriptResource" preCondition ="integratedMode" verb ="GET,HEAD" path ="ScriptResource.axd" type ="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</ handlers >
</ system.webServer >
< runtime >
< assemblyBinding xmlns ="urn:schemas-microsoft-com:asm.v1" >
< dependentAssembly >
< assemblyIdentity name ="System.Web.Extensions" publicKeyToken ="31bf3856ad364e35" />
< bindingRedirect oldVersion ="1.0.0.0-1.1.0.0" newVersion ="3.5.0.0" />
</ dependentAssembly >
< dependentAssembly >
< assemblyIdentity name ="System.Web.Extensions.Design" publicKeyToken ="31bf3856ad364e35" />
< bindingRedirect oldVersion ="1.0.0.0-1.1.0.0" newVersion ="3.5.0.0" />
</ dependentAssembly >
</ assemblyBinding >
</ runtime >
</ configuration >

补充知识 --- 重置Form表单的Action属性:

a. 自定义类RawHtmlForm继承自HtmlForm控件

b. 重写RenderAttribute()方法

ContractedBlock.gif ExpandedBlockStart.gif View Code
public class RawHtmlForm : System.Web.UI.HtmlControls.HtmlForm
{
protected override void RenderAttributes(System.Web.UI.HtmlTextWriter writer)
{
this .Action = Page.Request.RawUrl;
base .RenderAttributes(writer);
}
}

c. 在配置文件中, 指明用新控件RawHtmlForm替代HtmlForm控件, 这样在生成form标签时, 自动使用新控件代替旧控件.

ContractedBlock.gif ExpandedBlockStart.gif View Code
< system.web >
< pages >
< tagMapping >
< add tagType ="System.Web.UI.HtmlControls.HtmlForm" mappedTagType ="RawHtmlForm" />
</ tagMapping >
</ pages >
</ system.web >

第二种: 缓存为Html文件的技术(*.aspx页面的请求结果就是个html页面):

它的原理是客户端请求*.aspx文件, 如果在缓存文件夹中有对应名称的*.html文件, 则将请求地址替换为*.html的文件. 这样就不必走完全部的应用程序处理管道, 响应速度会大大提高; 如果缓存文件夹中没有对应的*.html文件, 则该请求会走完整个应用程序管道, 在应用程序管道中的页面处理部分将*.aspx页面的请求结果返回给客户端同时, 再以流的形式保存(另存)*.aspx请求结果到缓存文件中. 这样做的好处是加快网站的响应速度, 而一个快速响应的网站对提升SEO(Searching Engine Optimization)效果也是有一定帮助的. 这种手法是用对文件的IO操作代替费时的应用程序管道的操作, 对于那些访问量极高的页面, 我们甚至可以把*.aspx页面的请求结果直接保存到内存中, 这样连IO操作也省掉了, 但内存的有限性决定了我们不能够保存太多的页面在内存中, 只能保存那些访问量极高的少量页面.


缓存后替换:

以上我们实现了整页的缓存, 但是缓存完的数据是关于整个页面的, 是没办法修改其内容的. 仍然拿新闻页面来打比方: 如果我想在每个新闻页面中显示下当前日期和时间, 或者我想在每个新闻页面的头部和尾部添加广告, 针对这种大部分内容不变仅有少部分内容发生变化的情况, ASP.NET提供了缓存后替换功能.

缓存后替换功能可以将整个页面进行输出缓存, 但是特定的部分标记为不缓存. Substitution控件指定需要动态创建而不进行缓存的部分, 类似于占位符, 动态生成的内容将输出到Substitution控件所在的位置. ASP.NET为我们提供了3种方式的缓存后替换: a. 以声明的方式使用Substitution控件 b. 以编程的方式使用Substitution控件 c. 使用AdRotator控件.


a. 以声明的方式使用Substitution控件时: Substitution控件调用MethodName属性指定的方法, 该方法提供了在Substitution控件处显示的内容, 并且该方法必须返回字符串类型的结果, 而且必须在Page或UserControl类的代码中包含该控件指定的这个静态方法. MethodName指定的方法并需符合HttpResponseSubstitutionCallback委托的约定(以参数为HttpContext类型), 简言之就是MethodName指的方法, 必须是static、返回string、参数为HttpContext类型的方法.


b. 以编程的方式使用Substitution控件时: 可以将当前页或用户控件后台代码中的静态方法 或 任何对象上的静态方法的方法名, 传递给HttpResponse.WriteSubstitution()方法. 第一次请求该页的时候, WriteSubstitution方法调用HttpResponseSubstitutionCallback委托来产生输出, 之后将替换缓存区中的内容. 该方法会将客户端的缓存能力从public将为server, 从而使浏览器不在缓存而保证能够重新生成静态内容.


c. AdRotator服务器控件: 该服务器控件是在其内部支持缓存后替代功能. 如果将AdRotator控件放在页面上, 则每次请求时都会生成动态的广告. 因此, 包含AdRotator控件的页面仅能在服务器端缓存, 可以通过AdRotator的AdCreated事件对广告内容作高级的处理. 通过AdRotator的AdvertisementFile属性指定储存广告数据的文件, 通常是xml文件. 配置广告信息的xml的格式, 见示例文件XmlAdData.xml.

AdRotator的几个属性释义如下:

ImageUrl: 广告图片地址

NavigateUrl: 点击广告图片的链接地址

AlternateText: 鼠标放在图片上的提示文字

Keyword: 该广告的关键词

Impression: 权重, 广告的显示频率.

示例: 对于新闻类型的网站, 站内的大量文章内容发生改变的频率不是很高, 因此适合将这些文章内容缓存为静态的html页面, 以减少文章内容页重复生成过程的开销.

//CacheHtmlPageDemo/App_code/ CacheHtmlModule.cs    ---   若在CacheFile文件夹中, 存在缓存的*.html则返回客户端

ContractedBlock.gif ExpandedBlockStart.gif View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for CacheHtmlModule
/// </summary>
public class CacheHtmlModule : IHttpModule
{
public CacheHtmlModule()
{
//
// TODO: Add constructor logic here
//
}

#region IHttpModule Members

public void Dispose()
{
throw new NotImplementedException();
}

public void Init(HttpApplication application)
{
application.BeginRequest
+= new EventHandler(application_BeginRequest);
}

void application_BeginRequest( object sender, EventArgs e)
{
HttpApplication ha
= sender as HttpApplication;
HttpContext hc
= ha.Context;

// 相对于网站根节点~/的资源地址, 如: ~/default.aspx
if (hc.Request.AppRelativeCurrentExecutionFilePath.ToLower().EndsWith( " .aspx " ))
{
// 处理开头和结尾的"~/"、".aspx"、深层文件夹的"/", 并使用context.Request.Url.Query获得Url中的请求参数信息后处理请求参数
string filepath = " ~/CacheFile/ " + hc.Request.AppRelativeCurrentExecutionFilePath.ToLower().Replace( " .aspx " , "" ).Replace( " ~/ " , "" ).Replace( " / " , " _ " ) + hc.Request.Url.Query.Replace( " ? " , " _ " ).Replace( " & " , " _ " ) + " .html " ;
if (System.IO.File.Exists(hc.Server.MapPath(filepath)))
{
// 在缓存文件夹中能够找到静态的html文件
hc.RewritePath(filepath, false );
}
}
}

#endregion
}

//CacheHtmlPageDemo/App_code/HtmlPageBase.cs --- 若不存在缓存的*.html, 则走页面处理管道并将生成的页面保存到CacheFile文件夹中, 我们所要做的只是将页面后台的.cs文件中的类继承成自HtmlPageBase类而非原先的Page类.

ContractedBlock.gif ExpandedBlockStart.gif View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for HtmlPageBase
/// </summary>
public class HtmlPageBase : System.Web.UI.Page
{
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
// 生成的页面内容不但要保存到文件, 还要返回给浏览器. 所以不能直接用streamwriter
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw
= new System.Web.UI.HtmlTextWriter(sw);

// 调用基类的render方法, 将结果输出到StringWriter中
base .Render(htw);

htw.Flush();
htw.Close();

// 获得页面的内容
string pagecontent = sw.ToString();
sw.Close();
string filepath = this .Server.MapPath( " ~/CacheFile/ " ) + this .Request.AppRelativeCurrentExecutionFilePath.ToLower().Replace( " .aspx " , "" ).Replace( " ~/ " , "" ).Replace( " / " , " _ " ) + this .Request.Url.Query.Replace( " ? " , " _ " ).Replace( " & " , " _ " ) + " .html " ;
// 判断CacheFile文件夹是否存在
string cachefolder = System.IO.Path.GetDirectoryName(filepath);
if (System.IO.Directory.Exists(cachefolder))
{
System.IO.Directory.CreateDirectory(cachefolder);
}

// 保存页面内容到静态文件中
System.IO.StreamWriter swriter = new System.IO.StreamWriter(filepath);
swriter.Write(pagecontent);
swriter.Close();

// 将页面内容输出到浏览器中
Response.Write(pagecontent);
}

#region 不在IHttpModule中做任何处理, 而是在页面的Page_PreInit事件中查看缓存文件是否存在(理论上比IHttpModule要慢)
// protected override void OnPreInit(EventArgs e)
// {
// string filepath = "~/CacheFile/" + this.Request.AppRelativeCurrentExecutionFilePath.ToLower().Replace(".aspx", "").Replace("~/", "").Replace("/", "_") + this.Request.Url.Query.Replace("?", "_").Replace("&", "_") + ".html";
// if (System.IO.File.Exists(filepath))
// {
// // 在CacheFile中能够找到缓存的静态页面
// this.Server.Transfer(filepath);
// }
// base.OnPreInit(e);
// }
#endregion
}

//CacheHtmlPageDemo/Default.aspx

ContractedBlock.gif ExpandedBlockStart.gif View Code
<% @ Page Language = " C# " AutoEventWireup = " true " CodeFile = " Default.aspx.cs " Inherits = " _Default " %>

<! 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 runat ="server" >
< title ></ title >
</ head >
< body >
< p >< a href ="News1.aspx" > 新闻1 </ a ></ p >< br />
< p >< a href ="News2.aspx" > 新闻2 </ a ></ p >< br />
< p >< a href ="News3.aspx" > 新闻3 </ a ></ p >< br />
</ body >
</ html >

//CacheHtmlPageDemo/News1.aspx

ContractedBlock.gif ExpandedBlockStart.gif View Code
<% @ Page Language = " C# " AutoEventWireup = " true " CodeFile = " News1.aspx.cs " Inherits = " NewOne " %>

<! 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 runat ="server" >
< title ></ title >
</ head >
< body >
< h1 > This is the 1st page of News Channel. </ h1 >
</ body >
</ html >

//CacheHtmlPageDemo/News3.aspx , 缓存后替换示例, 该页面添加了@OutputCache页面指令, 且后台代码继承自默认的Page类.

ContractedBlock.gif ExpandedBlockStart.gif View Code
<% @ Page Language = " C# " AutoEventWireup = " true " CodeFile = " News3.aspx.cs " Inherits = " News3 " %>

<% @ OutputCache Duration = " 10 " VaryByParam = " None " %>

<! 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 runat ="server" >
< title ></ title >
</ head >
< body >
< asp:Label id ="time" runat ="server" text ="用于对比的Label显示的时间:" ></ asp:Label >
< hr />
< h1 > This is the 3rd page of News Channel. </ h1 >
< hr />
< asp:substitution id ="substitution1" runat ="server" MethodName ="GetTimeNow" ></ asp:substitution >< br />
< hr />
< asp:AdRotator ID ="AdRotator1" AdvertisementFile ="~/Data/XmlAdData.xml.xml" runat ="server" />
</ body >
</ html >

//CacheHtmlPageDemo/App_Data/XmlAdData.xml, 为简便而使用xml, 若用数据库也可以, 将XML节点对应表的字段(随便两张图片就行).

ContractedBlock.gif ExpandedBlockStart.gif View Code
<? xml version="1.0" encoding="utf-8" ?>
< Advertisements >
< Ad >
< AlternateText > 美女1 </ AlternateText >
< ImageUrl > ~/Data/ad1.jpg </ ImageUrl >
< NavigateUrl > http://www.baidu.com </ NavigateUrl >
< Kayword > 1 </ Kayword >
< Impressions > 50 </ Impressions >
</ Ad >

< Ad >
< AlternateText > 美女2 </ AlternateText >
< ImageUrl > ~/Data/ad2.jpg </ ImageUrl >
< NavigateUrl > http://www.baidu.com </ NavigateUrl >
< Kayword > 1 </ Kayword >
< Impressions > 50 </ Impressions >
</ Ad >
</ Advertisements >

// CacheHtmlPageDemo/web.config

ContractedBlock.gif ExpandedBlockStart.gif View Code
<? xml version="1.0" ?>
<!--
Note: As an alternative to hand editing this file you can use the
web admin tool to configure settings for your application. Use
the Website->Asp.Net Configuration option in Visual Studio.
A full list of settings and comments can be found in
machine.config.comments usually located in
\Windows\Microsoft.Net\Framework\v2.x\Config
-->
< configuration >
< configSections >
< sectionGroup name ="system.web.extensions" type ="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" >
< sectionGroup name ="scripting" type ="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" >
< section name ="scriptResourceHandler" type ="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission ="false" allowDefinition ="MachineToApplication" />
< sectionGroup name ="webServices" type ="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" >
< section name ="jsonSerialization" type ="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission ="false" allowDefinition ="Everywhere" />
< section name ="profileService" type ="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission ="false" allowDefinition ="MachineToApplication" />
< section name ="authenticationService" type ="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission ="false" allowDefinition ="MachineToApplication" />
< section name ="roleService" type ="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission ="false" allowDefinition ="MachineToApplication" />
</ sectionGroup >
</ sectionGroup >
</ sectionGroup >
</ configSections >
< appSettings />
< connectionStrings />
< system.web >
<!--
Set compilation debug="true" to insert debugging
symbols into the compiled page. Because this
affects performance, set this value to true only
during development.
-->
< compilation debug ="true" >
< assemblies >
< add assembly ="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
< add assembly ="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
< add assembly ="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
< add assembly ="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
</ assemblies >
</ compilation >
<!--
The <authentication> section enables configuration
of the security authentication mode used by
ASP.NET to identify an incoming user.
-->
< authentication mode ="Windows" />
<!--
The <customErrors> section enables configuration
of what to do if/when an unhandled error occurs
during the execution of a request. Specifically,
it enables developers to configure html error pages
to be displayed in place of a error stack trace.

<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
-->
< pages >
< controls >
< add tagPrefix ="asp" namespace ="System.Web.UI" assembly ="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
< add tagPrefix ="asp" namespace ="System.Web.UI.WebControls" assembly ="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</ controls >
</ pages >
< httpHandlers >
< remove verb ="*" path ="*.asmx" />
< add verb ="*" path ="*.asmx" validate ="false" type ="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
< add verb ="*" path ="*_AppService.axd" validate ="false" type ="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
< add verb ="GET,HEAD" path ="ScriptResource.axd" type ="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate ="false" />
</ httpHandlers >
< httpModules >
< add name ="ScriptModule" type ="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
< add name ="Cachehtml" type ="CacheHtmlModule" />
</ httpModules >
</ system.web >
< system.codedom >
< compilers >
< compiler language ="c#;cs;csharp" extension =".cs" warningLevel ="4" type ="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
< providerOption name ="CompilerVersion" value ="v3.5" />
< providerOption name ="WarnAsError" value ="false" />
</ compiler >
< compiler language ="vb;vbs;visualbasic;vbscript" extension =".vb" warningLevel ="4" type ="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
< providerOption name ="CompilerVersion" value ="v3.5" />
< providerOption name ="OptionInfer" value ="true" />
< providerOption name ="WarnAsError" value ="false" />
</ compiler >
</ compilers >
</ system.codedom >
<!--
The system.webServer section is required for running ASP.NET AJAX under Internet
Information Services 7.0. It is not necessary for previous version of IIS.
-->
< system.webServer >
< validation validateIntegratedModeConfiguration ="false" />
< modules >
< remove name ="ScriptModule" />
< add name ="ScriptModule" preCondition ="managedHandler" type ="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</ modules >
< handlers >
< remove name ="WebServiceHandlerFactory-Integrated" />
< remove name ="ScriptHandlerFactory" />
< remove name ="ScriptHandlerFactoryAppServices" />
< remove name ="ScriptResource" />
< add name ="ScriptHandlerFactory" verb ="*" path ="*.asmx" preCondition ="integratedMode" type ="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
< add name ="ScriptHandlerFactoryAppServices" verb ="*" path ="*_AppService.axd" preCondition ="integratedMode" type ="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
< add name ="ScriptResource" preCondition ="integratedMode" verb ="GET,HEAD" path ="ScriptResource.axd" type ="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</ handlers >
</ system.webServer >
< runtime >
< assemblyBinding xmlns ="urn:schemas-microsoft-com:asm.v1" >
< dependentAssembly >
< assemblyIdentity name ="System.Web.Extensions" publicKeyToken ="31bf3856ad364e35" />
< bindingRedirect oldVersion ="1.0.0.0-1.1.0.0" newVersion ="3.5.0.0" />
</ dependentAssembly >
< dependentAssembly >
< assemblyIdentity name ="System.Web.Extensions.Design" publicKeyToken ="31bf3856ad364e35" />
< bindingRedirect oldVersion ="1.0.0.0-1.1.0.0" newVersion ="3.5.0.0" />
</ dependentAssembly >
</ assemblyBinding >
</ runtime >
</ configuration >

使用缓存时, 关于缓存内容的考量:

a. 没有必要缓存用户相关页面, 这会存储很多低点击率的页面

b. 缓存那些频繁请求, 但是内容更新不太频繁或者提供过期内容也影响不大的页面.

c. 生成操作很昂贵的页面, 如: 电子商务网站中的, 分类显示和报表显示页面的生成操作.

d. 内存空间有限, 所以只能缓存那些占用空间小的内容.

e. 对于Postback的响应不应该被缓存, 因为他们依赖于post请求参数.

5. 在页面处理管道或通过IHttpHandler在处理程序中做数据缓存.


说起数据缓存, 肯定跟网站应用程序的数据来源有关了, 需要被缓存的那部分数据当然是放在Cache中. 那么数据本身要么是存放在文件中, 要么是存放在数据库中, 因此对应于这两种数据载体, .net提供了2种依赖机制: 一种是基于文件和目录的CacheDependency, 一种是基于数据库的SqlDependency, SqlDependency是数据库和程序之间的依赖关系, 此外微软还提供了继承自CacheDependency的SqlCacheDependency类, 用来建立数据库和程序缓存之间的依赖关系. 这种缓存依赖解决个什么问题呢, 数据不是已经缓存了吗? 没错, 我们是缓存了数据, 但是如果原始数据发生变化怎么办? 缓存依赖就是当数据发生变化时, 自动清除缓存中数据的这么一种机制, 接下来的下一次请求必然要从新执行读取数据的操作.

缓存依赖执行的操作是删除缓存内容, 这样下一次请求势必会从新获取数据. 这与”缓存后替换”功能是不一样的, 缓存后替换功能是用读取的新数据替换缓存页面的一部分内容.


第一种: 基于文件和目录的CacheDependency是比较简单的, 留意缓存依赖的过期时间、缓存项的优先级、以及删除通知(当被缓存的数据从缓存中移除时激发的事件)即可.


值得注意的地方: 删除通知的回调方法(委托)的回调时机是不可预知的, 很有可能在回调的时候, 页面的生成过程已经完成, 这时候根本没有HttpContext对象, 所以对缓存的操作只能通过HttpRuntime的Cache属性来获得. 而且, 不能在页面上使用实例方法来作为回调方法, 因为回调方法会阻止页面对象的垃圾回收, 内存资源将很快消耗光.

//DataCacheDemo/App_Code/ FileCacheManager.cs

ContractedBlock.gif ExpandedBlockStart.gif View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for FileCacheManager
/// </summary>
public class FileCacheManager
{
public FileCacheManager()
{
//
// TODO: Add constructor logic here
//
}

public static string GetDataFromFile()
{
string msg = string .Empty;
string datapath = HttpContext.Current.Server.MapPath( " ~/App_Data/TextFileData.txt " );

// 1. 从缓存中读取数据
// msg = HttpContext.Current.Cache["message"] as string;
msg = HttpRuntime.Cache[ " message " ] as string ;

if (msg == null )
{
// 2. 创建缓存依赖对象
System.Web.Caching.CacheDependency cd = new System.Web.Caching.CacheDependency(datapath);

// 从文本文件中读取数据
using (System.IO.StreamReader sr = new System.IO.StreamReader(datapath))
{
msg
= sr.ReadToEnd();
}
HttpRuntime.Cache.Add(
" message " , msg, cd, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan( 0 , 1 , 0 ), System.Web.Caching.CacheItemPriority.Normal, new System.Web.Caching.CacheItemRemovedCallback(CallbackMethod));
}

return msg;
}

// 当被缓存的数据从缓存中移除时, 激发的事件. 缓存依赖的回调方法必须是静态方法, 实例方法会阻止垃圾回收.
private static void CallbackMethod( string key, object value, System.Web.Caching.CacheItemRemovedReason reason)
{
// 回调方法执行时, 可能根本不存在HttpContext对象, 这时应该是用HttpRuntime对象获得缓存的引用
}
}

//DataCacheDemo/App_Data/TextFileData.txt, 文字内容随意

//DataCacheDemo/CacheDependency.aspx

ContractedBlock.gif ExpandedBlockStart.gif View Code
<% @ Page Language = " C# " AutoEventWireup = " true " CodeFile = " CacheDependency.aspx.cs " Inherits = " CacheDependency " %>

<! 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 runat ="server" >
< title ></ title >
</ head >
< body >
< span > 基于文件和目录的缓存依赖: </ span >
< hr />
< asp:Label ID ="lbl_msg" runat ="server" Text ="Label" ></ asp:Label >
</ body >
</ html >

//DataCacheDemo/CacheDependency.aspx.cs

ContractedBlock.gif ExpandedBlockStart.gif View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class CacheDependency : System.Web.UI.Page
{
protected void Page_Load( object sender, EventArgs e)
{
this .lbl_msg.Text = FileCacheManager.GetDataFromFile();
}
}

第二种: 基于Sql的缓存依赖有两种实现: a. 基于轮询的实现 和 b. 基于通知的实现(仅支持Ms Sql 2005 以上的版本).


  1. 基于轮询的实现: 就是由 应用程序 每隔一定时间去访问数据库, 查看数据是否发生变化.

注意: 轮询的实际操作, 不可能每次都去查询整个数据库, 轮询机制实际上是通过触发器来维护一张监控表来实现的.


具体操作如下:

创建一张监控信息表, 表的字段主要有两个(被监控的表名, int型字段用来表示数据是否发生变化).

在被监控表上建立触发器, 当表的内容发生变化时, 修改监控表的int字段, 可以通过表的Insert、Delete、Update触发器实现.

对于除Sql Server以外的数据库, 如Oracle、MySql等可采用类似的办法建立轮询机制或通知机制(当然Sql Server也可以这么做). 而Sql Server数据库已经由微软提供了一套轮询实现机制.

(1) . 工具位置: c:\Windows\Microsoft.Net\Framework\v2.0.50727\aspnet_regsql.exe

该工具的参数信息如下(区分大小写):

-S 数据库服务器的名称或ip地址

-E 使用集成验证方式登录数据库

-U 用户名

-P 密码

-d 数据库名称, 如不提供则使用aspnetdb数据库

-ed 为数据库打开Sql缓存依赖支持

-dd 关闭数据库的Sql缓存依赖支持

-et 指定Sql缓存依赖使用的表, 需要使用-t指定表名

-dt 禁用Sql缓存依赖使用的表, 需要使用-t指定表名

-t 指定表名

-lt 列出启用缓存依赖的表名

示例:

启用数据库缓存依赖: aspnet_regsql –S .\MSSQLServer –E –d northwind –ed

启动对被监控表的监控: aspnet_regsql –S .\MSSQLServer –E –d northwind –t calendar –et

列出启用了缓存依赖的表: aspnet_regsql –S .\MSSQLServer –E –d northwind –lt


(2). 运用aspnet_regsql工具配置完数据库后, 还需要在配置文件中增加轮询的设置. sqlCacheDependency enable属性为”true”表示开启抡起机制, polltime设置以毫秒为单位的轮询间隔(>= 500ms, 默认为1分钟).

ContractedBlock.gif ExpandedBlockStart.gif View Code
< system.web >
< caching >
< sqlCacheDependency enabled ="true" >
< databases >
< add name ="northwindCache" connectionStringName ="MsSql" pollTime ="60000" />
</ databases >
</ sqlCacheDependency >
</ caching >
</ system.web >

SqlCacheDependency表示Sql缓存依赖对象, 即支持轮询机制也支持通知机制. SqlCacheDependency scd = new SqlCacheDependency(“配置文件中的数据库那一项的名称, 如northwindCache”, “被监控的表名”);


当构造缓存依赖对象时, 可以通过AggregateCacheDependency创建多个依赖的组合, 在该组合中任一依赖发生变化时将使缓存失效. 组合的缓存依赖内部为一个集合, 例如: 缓存的数据是依赖于Customers和Orders两张表, 我们可以建立2个缓存依赖对象, 并将其添加到一个AggregateCacheDependency对象中, 这时只要任何缓存依赖发生变化, 缓存数据将会失效.

//涉及Sql的相关操作, MsSqlCommand.txt

ContractedBlock.gif ExpandedBlockStart.gif View Code
###################MS SQL Server 轮询机制########################

if exists ( select * from sysobjects where [ name ] = ' SP_GetAllCustomersWithOrders ' and [ type ] = ' P ' )
drop procedure SP_GetAllCustomersWithOrders
go
create procedure SP_GetAllCustomersWithOrders
as
begin
select * from customers c inner join orders o on c.customerid = o.customerid
end
go

-- 调用
exec SP_GetAllCustomersWithOrders


-- 插入一条数据
insert into Customers( CustomerID, CompanyName, ContactName, ContactTitle, Address, City, PostalCode, Country, Phone)
values ( ' ZHANG ' , ' CAIT Beijing ' , ' Jalen Zhang ' , ' Owner ' , ' China Beijing ' , ' Beijing ' , ' 100088 ' , ' China ' , ' 82240389 ' )
go


delete from Customers where CustomerID = ' ZHANG '
go



###################MS SQL Server 通知机制########################
-- 产看是否开启通知机制
select databasepropertyex( ' MSPetShop4 ' , ' IsBrokerEnabled ' )

-- 开启Sql Server 2005数据库通知机制
alter database MSPetShop4 set enable_broker
go

-- 通知机制只支持最简单的Select语句
SELECT ProductId, CategoryId, Name, Descn, Image FROM dbo.Product

update product set Descn = ' HelloWorld ' where productid = ' BD-01 ' and categoryid = ' BIRDS '


//DataCacheDemo/App_Code/IDALFactory.cs

ContractedBlock.gif ExpandedBlockStart.gif View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for IDALFactory
/// </summary>
public interface IDAL
{
void ExecuteNonQuery( string sqlstr, System.Data.CommandType comtype, params object [] param);
System.Data.DataSet ExecuteDataSet(
string sqlstr, System.Data.CommandType comtype, params object [] param);
object ExecuteReader( string sqlstr, System.Data.CommandType comtype, params object [] param);
}

public class IDALFactory
{
public static IDAL GetDAL()
{
string dbtype = System.Configuration.ConfigurationManager.AppSettings[ " DBType " ];
switch (dbtype)
{
case " MsSql " :
return new SqlDAL();
case " Oracle " :
return new OracleDAL();
default :
return null ;
}
}

}

//DataCacheDemo/App_Code/SqlDAL.cs

ContractedBlock.gif ExpandedBlockStart.gif View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for SqlDAL
/// </summary>
public class SqlDAL : IDAL
{
readonly string constr = System.Configuration.ConfigurationManager.ConnectionStrings[ " MsSql " ].ConnectionString;
System.Data.SqlClient.SqlConnection connection;
System.Data.SqlClient.SqlCommand command;

public SqlDAL()
{
connection
= new System.Data.SqlClient.SqlConnection(constr);
command
= new System.Data.SqlClient.SqlCommand();
command.Connection
= connection;
}

#region IDALFactory Members

public void ExecuteNonQuery( string sqlstr, System.Data.CommandType comtype, params object [] param)
{
command.CommandText
= sqlstr;
command.CommandType
= comtype;
if (comtype == System.Data.CommandType.StoredProcedure)
{
for ( int i = 0 ; i < param.Length; i ++ )
{
command.Parameters.Add(param[i]
as System.Data.SqlClient.SqlParameter);
}
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException se)
{ }
finally
{
if (connection.State == System.Data.ConnectionState.Open)
{
connection.Close();
}
}
}
}

public System.Data.DataSet ExecuteDataSet( string sqlstr, System.Data.CommandType comtype, params object [] param)
{
System.Data.DataSet ds
= new System.Data.DataSet();
command.CommandText
= sqlstr;
command.CommandType
= comtype;
if (comtype == System.Data.CommandType.StoredProcedure)
{
for ( int i = 0 ; i < param.Length; i ++ )
{
command.Parameters.Add(param[i]
as System.Data.SqlClient.SqlParameter);
}
try
{
// DataSet是无连接的
System.Data.SqlClient.SqlDataAdapter sda = new System.Data.SqlClient.SqlDataAdapter(command);
sda.Fill(ds);
}
catch (System.Data.SqlClient.SqlException se)
{ }
}
return ds;
}

public object ExecuteReader( string sqlstr, System.Data.CommandType comtype, params object [] param)
{
command.CommandText
= sqlstr;
command.CommandType
= comtype;
System.Data.SqlClient.SqlDataReader sdr
= null ;
if (comtype == System.Data.CommandType.StoredProcedure)
{
for ( int i = 0 ; i < param.Length; i ++ )
{
command.Parameters.Add(param[i]
as System.Data.SqlClient.SqlParameter);
}
try
{
connection.Open();
sdr
= command.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
}
catch (System.Data.SqlClient.SqlException se)
{ }
}
return sdr;
}

#endregion
}

//DataCacheDemo/App_Code/OracleDAL.cs

ContractedBlock.gif ExpandedBlockStart.gif View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for OracleDAL
/// </summary>
public class OracleDAL : IDAL
{
readonly string constr = System.Configuration.ConfigurationManager.ConnectionStrings[ " Oracle " ].ConnectionString;
Oracle.DataAccess.Client.OracleConnection connection;
Oracle.DataAccess.Client.OracleCommand command;
public OracleDAL()
{
connection
= new Oracle.DataAccess.Client.OracleConnection(constr);
command
= new Oracle.DataAccess.Client.OracleCommand();
command.Connection
= connection;
}

#region IDALFactory Members

public void ExecuteNonQuery( string sqlstr, System.Data.CommandType comtype, params object [] param)
{
command.CommandText
= sqlstr;
command.CommandType
= comtype;
if (comtype == System.Data.CommandType.StoredProcedure)
{
for ( int i = 0 ; i < param.Length; i ++ )
{
command.Parameters.Add(param[i]
as Oracle.DataAccess.Client.OracleParameter);
}
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Oracle.DataAccess.Client.OracleException oex)
{
}
finally
{
if (connection.State == System.Data.ConnectionState.Open)
{
connection.Close();
}
}
}
}

public System.Data.DataSet ExecuteDataSet( string sqlstr, System.Data.CommandType comtype, params object [] param)
{
command.CommandText
= sqlstr;
command.CommandType
= comtype;
if (command.CommandType == System.Data.CommandType.StoredProcedure)
{
for ( int i = 0 ; i < param.Length; i ++ )
{
command.Parameters.Add(param[i]
as Oracle.DataAccess.Client.OracleParameter);
}
}
System.Data.DataSet ds
= new System.Data.DataSet();
Oracle.DataAccess.Client.OracleDataAdapter oda
= new Oracle.DataAccess.Client.OracleDataAdapter(command);

// DataSet是无连接的
try
{
oda.Fill(ds);
}
catch (Oracle.DataAccess.Client.OracleException oe)
{ }
return ds;
}

public object ExecuteReader( string sqlstr, System.Data.CommandType comtype, params object [] param)
{
Oracle.DataAccess.Client.OracleDataReader odr
= null ;
command.CommandText
= sqlstr;
command.CommandType
= comtype;
if (comtype == System.Data.CommandType.StoredProcedure)
{
for ( int i = 0 ; i < param.Length; i ++ )
{
command.Parameters.Add(param[i]
as Oracle.DataAccess.Client.OracleParameter);
}
}
try
{
connection.Open();
odr
= command.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
}
catch (Oracle.DataAccess.Client.OracleException oe)
{
}
return odr;
}

#endregion
}

//DataCacheDemo/App_Code/pollingSqlDependency.aspx

ContractedBlock.gif ExpandedBlockStart.gif View Code
<% @ Page Language = " C# " AutoEventWireup = " true " CodeFile = " pollingSqlDependency.aspx.cs " Inherits = " pollingSqlDependency " %>

<! 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 runat ="server" >
< title ></ title >
</ head >
< body >
< span > 基于通知机制的SQL缓存依赖: </ span >
< br />
< h3 > MS SQL Server 轮询机制 </ h3 >< br />
< hr />
< form id ="form1" runat ="server" >
< asp:GridView ID ="grd_customerandorder" runat ="server" >
</ asp:GridView >
</ form >
</ body >
</ html >

//DataCacheDemo/App_Code/pollingSqlDependency.aspx.cs

ContractedBlock.gif ExpandedBlockStart.gif View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class pollingSqlDependency : System.Web.UI.Page
{
protected void Page_Load( object sender, EventArgs e)
{
BindData();
}

protected void BindData()
{
// 1. 从缓存中读取数据
System.Data.DataTable dt = HttpContext.Current.Cache[ " CustomerWithOrders " ] as System.Data.DataTable;
if (dt == null )
{
IDAL dal
= IDALFactory.GetDAL();
dt
= dal.ExecuteDataSet( " SP_GetAllCustomersWithOrders " , System.Data.CommandType.StoredProcedure).Tables[ 0 ];

// 2. 创建缓存依赖对象
System.Web.Caching.SqlCacheDependency scd = new System.Web.Caching.SqlCacheDependency( " CustomerCache " , " Customers " );

System.Web.Caching.SqlCacheDependency scd2
= new System.Web.Caching.SqlCacheDependency( " CustomerCache " , " Orders " );

System.Web.Caching.AggregateCacheDependency acd
= new System.Web.Caching.AggregateCacheDependency();
acd.Add(scd,scd2);

// 3. 保存数据到缓存
// HttpContext.Current.Cache.Add("CustomerWithOrders", dt, scd, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 5, 0), System.Web.Caching.CacheItemPriority.Normal, new System.Web.Caching.CacheItemRemovedCallback(CallbackMethod));
HttpContext.Current.Cache.Add( " CustomerWithOrders " , dt, acd, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan( 0 , 5 , 0 ), System.Web.Caching.CacheItemPriority.Normal, new System.Web.Caching.CacheItemRemovedCallback(CallbackMethod));
}
this .grd_customerandorder.DataSource = dt;
this .grd_customerandorder.DataBind();
}

// 当被缓存的数据从缓存中移除时, 激发的事件. 缓存依赖的回调方法必须是静态方法, 实例方法会阻止垃圾回收.
private static void CallbackMethod( string key, object value, System.Web.Caching.CacheItemRemovedReason reason)
{
// 回调方法执行时, 可能根本不存在HttpContext对象, 这时应该是用HttpRuntime对象获得缓存的引用
}
}

//DataCacheDemo/App_Code/web.config

ContractedBlock.gif ExpandedBlockStart.gif View Code
<? xml version="1.0" ?>
<!--
Note: As an alternative to hand editing this file you can use the
web admin tool to configure settings for your application. Use
the Website->Asp.Net Configuration option in Visual Studio.
A full list of settings and comments can be found in
machine.config.comments usually located in
\Windows\Microsoft.Net\Framework\v2.x\Config
-->
< configuration >
< configSections >
< sectionGroup name ="system.web.extensions" type ="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" >
< sectionGroup name ="scripting" type ="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" >
< section name ="scriptResourceHandler" type ="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission ="false" allowDefinition ="MachineToApplication" />
< sectionGroup name ="webServices" type ="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" >
< section name ="jsonSerialization" type ="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission ="false" allowDefinition ="Everywhere" />
< section name ="profileService" type ="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission ="false" allowDefinition ="MachineToApplication" />
< section name ="authenticationService" type ="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission ="false" allowDefinition ="MachineToApplication" />
< section name ="roleService" type ="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission ="false" allowDefinition ="MachineToApplication" />
</ sectionGroup >
</ sectionGroup >
</ sectionGroup >
</ configSections >
< appSettings >
< add key ="DBType" value ="MsSql" />
</ appSettings >
< connectionStrings >
< add name ="MsSql" connectionString ="data source=.;database=northwind;user id=sa;password=sa" />
< add name ="Oracle" connectionString ="data source=orcl;user id=hr;password=hr" />
<!-- 使用Northwind演示Northwind不成功, 估计数据库可能有问题 -->
< add name ="MsSqlNotification" connectionString ="data source=.;database=MSPetShop4;user id=sa;password=sa" />
</ connectionStrings >
< system.web >
< caching >
< sqlCacheDependency enabled ="true" >
< databases >
< add name ="CustomerCache" connectionStringName ="MsSql" pollTime ="60000" />
</ databases >
</ sqlCacheDependency >
</ caching >
<!--
Set compilation debug="true" to insert debugging
symbols into the compiled page. Because this
affects performance, set this value to true only
during development.
-->
< compilation debug ="true" >
< assemblies >
< add assembly ="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
< add assembly ="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
< add assembly ="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
< add assembly ="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
< add assembly ="Oracle.DataAccess, Version=10.2.0.100, Culture=neutral, PublicKeyToken=89B483F429C47342" /></ assemblies >
</ compilation >
<!--
The <authentication> section enables configuration
of the security authentication mode used by
ASP.NET to identify an incoming user.
-->
< authentication mode ="Windows" />
<!--
The <customErrors> section enables configuration
of what to do if/when an unhandled error occurs
during the execution of a request. Specifically,
it enables developers to configure html error pages
to be displayed in place of a error stack trace.

<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
-->
< pages >
< controls >
< add tagPrefix ="asp" namespace ="System.Web.UI" assembly ="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
< add tagPrefix ="asp" namespace ="System.Web.UI.WebControls" assembly ="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</ controls >
</ pages >
< httpHandlers >
< remove verb ="*" path ="*.asmx" />
< add verb ="*" path ="*.asmx" validate ="false" type ="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
< add verb ="*" path ="*_AppService.axd" validate ="false" type ="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
< add verb ="GET,HEAD" path ="ScriptResource.axd" type ="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate ="false" />
</ httpHandlers >
< httpModules >
< add name ="ScriptModule" type ="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</ httpModules >
</ system.web >
< system.codedom >
< compilers >
< compiler language ="c#;cs;csharp" extension =".cs" warningLevel ="4" type ="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
< providerOption name ="CompilerVersion" value ="v3.5" />
< providerOption name ="WarnAsError" value ="false" />
</ compiler >
< compiler language ="vb;vbs;visualbasic;vbscript" extension =".vb" warningLevel ="4" type ="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
< providerOption name ="CompilerVersion" value ="v3.5" />
< providerOption name ="OptionInfer" value ="true" />
< providerOption name ="WarnAsError" value ="false" />
</ compiler >
</ compilers >
</ system.codedom >
<!--
The system.webServer section is required for running ASP.NET AJAX under Internet
Information Services 7.0. It is not necessary for previous version of IIS.
-->
< system.webServer >
< validation validateIntegratedModeConfiguration ="false" />
< modules >
< remove name ="ScriptModule" />
< add name ="ScriptModule" preCondition ="managedHandler" type ="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</ modules >
< handlers >
< remove name ="WebServiceHandlerFactory-Integrated" />
< remove name ="ScriptHandlerFactory" />
< remove name ="ScriptHandlerFactoryAppServices" />
< remove name ="ScriptResource" />
< add name ="ScriptHandlerFactory" verb ="*" path ="*.asmx" preCondition ="integratedMode" type ="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
< add name ="ScriptHandlerFactoryAppServices" verb ="*" path ="*_AppService.axd" preCondition ="integratedMode" type ="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
< add name ="ScriptResource" preCondition ="integratedMode" verb ="GET,HEAD" path ="ScriptResource.axd" type ="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</ handlers >
</ system.webServer >
< runtime >
< assemblyBinding xmlns ="urn:schemas-microsoft-com:asm.v1" >
< dependentAssembly >
< assemblyIdentity name ="System.Web.Extensions" publicKeyToken ="31bf3856ad364e35" />
< bindingRedirect oldVersion ="1.0.0.0-1.1.0.0" newVersion ="3.5.0.0" />
</ dependentAssembly >
< dependentAssembly >
< assemblyIdentity name ="System.Web.Extensions.Design" publicKeyToken ="31bf3856ad364e35" />
< bindingRedirect oldVersion ="1.0.0.0-1.1.0.0" newVersion ="3.5.0.0" />
</ dependentAssembly >
</ assemblyBinding >
</ runtime >
</ configuration >

基于Oracle实现轮询操作, 关键点就是对监控表的操作及触发器的编写. 这部分代码我没有写, 但它和Oracle通知机制的缓存依赖很像(见基于通知的缓存依赖Oracle示例). 我说个思路: 首先仍是创建监控表, 之后在被监控表上创建触发器, 对该表做的Insert、Update、Delete操作都会修改监控表(在我的基于通知的缓存依赖Oracle示例中, 我制作了个函数完成添加监控表记录、添加被监控表触发器、以及创建本地文件的操作). 最后, 我们可以再Galobal.asax的Application_Start事件中开辟子线程, 在子线程中读取配置文件中的事件设置, 定期去读取监控表的数据.


再具体点就是, 我们应该事先缓存监控表, 在子线程读取监控表数据后, 比较两个DataTable的内容, 找出发生变化的表的名字. 然后利用索引器查看缓存中是否有以这个表名作key的缓存项, 如果有的话清空这个缓存项, 没有则什么也不做. 大体思路是这样, 代码可以参考Orale的通知机制的实现, 这篇已经写了很久了, 不想再写了.


2. 基于通知的实现: 当数据发生变化时, 由数据库直接通知应用程序. 虽然, 通知机制不需要使用工具做数据库准备工作, 也不需要在配置文件中做任何修改, 但是通知机制只能应用在Ms Sql Server 2005以上的版本中.


具体操作:

使用命令启动数据库通知机制(默认是开启状态, 请务必先检查): alter database 数据库名称 set enable_broker

在Global.asax文件中的Application_Start和Application_End事件中分别设置开启和结束SqlDependency的监听.

通过一个SqlCommand对象来获取数据库查询通知, 该SqlCommand对象必须满足条件, 第一是数据库的表名必须是完全限定名(如: dbo.Region), 第二是Select语句必须显示执行列名, 不能用*、top函数等, 即只能是最简单的Select语句.

构造缓存依赖对象, SqlCacheDependency scd = new SqlCacheDependency(command);

示例:

//涉及Sql的相关操作, OracleCommand.txt.txt

ContractedBlock.gif ExpandedBlockStart.gif View Code
select username form all_users

alter user hr identified by hr account unlock

exit后, 以hr登陆

select table_name from user_tables

select * from regions

create table table_monitor(
table_name
varchar2 ( 50 ),
constraint pk_table_monitor primary key (table_name),
count number ( 8 ) default ( 0 ),
create_date date
default (sysdate)
)

// Triger的写法, 后边用一个函数完成添加监控记录、触发器及创建文件的操作.
create or replace trigger tg_monitor_REGIONS
after
insert or delete or update on REGIONS
declare
file_handle utl_file.file_type;
v_count
number ( 8 );
begin
update table_monitor set count = count + 1 where table_name = ' REGIONS ' ;
select count into v_count from table_monitor where table_name = ' REGIONS ' ;
file_handle :
= utl_file.fopen( ' PIC_FILE_DIR ' , ' REGIONS.txt ' , ' w ' );
utl_file.putf(file_handle,to_char(v_count));
utl_file.fclose(file_handle);
end tg_table_monitor;


// 用函数添加表名到监事表的同时, 也添加了触发器和创建了记录表信息的文件, 用于在插入数据时, 维护本地的一个文本文件, 配合CacheDependency实现通知机制
// 注意: PL / SQL调试, 需要执行grant debug connect Session, create trigger , create any directory to hr;
// 注意: 添加PRAGMA AUTONOMOUS_TRANSACTION自治事务是为了在select句子中使用insert、 delete 、update语句
// 注意: 必须确保服务器目录上有orcltmp这个目录
create or replace function fn_addToMonitor(
p_tablename
varchar2
)
return varchar2
is
PRAGMA AUTONOMOUS_TRANSACTION;
v_file
varchar2 ( 500 );
v_sql
varchar2 ( 500 );
begin
insert into table_monitor(table_name) values (p_tablename);
v_file :
= ' create or replace directory PID_FILE_DIR as '' c:\orcltmp ''' ;
execute immediate v_file;
v_sql :
= ' create or replace trigger tg_monitor_ ' || p_tablename || chr( 10 ) || ' after insert or delete or update on ' || p_tablename || chr( 10 ) || ' declare ' || chr( 10 ) || ' file_handle utl_file.file_type; ' || chr( 10 ) || ' v_count number(8); ' || chr( 10 ) || ' begin ' || chr( 10 ) || ' update table_monitor set count = count + 1 where table_name = ''' || p_tablename || ''' ; ' || chr( 10 ) || ' select count into v_count from table_monitor where table_name= ''' || p_tablename || ''' ; ' || chr( 10 ) || ' file_handle := utl_file.fopen( '' PIC_FILE_DIR '' , ''' || p_tablename || ' .txt '' , '' w '' ); ' || chr( 10 ) || ' utl_file.putf(file_handle,to_char(v_count)); ' || chr( 10 ) || ' utl_file.fclose(file_handle); ' || chr( 10 ) || ' end tg_table_monitor; ' ;
execute immediate v_sql;
commit ;
return ' Success! ' ;
exception
when others then
rollback ;
return ' Failure! ' ;
end ;
// 执行
select fn_addToMonitor( ' REGIONS ' ) from dual

// 测试时, 对Regions的修改需要使用事务, 否则DML操作在Oracle中不会提交, 导致页面结果不变
declare
begin
insert into regions(region_id,region_name) values ( 6 , ' WelCome ' );
commit ;
exception
when others then
rollback ;
end ;

//DataCacheDemo/Global.asax

ContractedBlock.gif ExpandedBlockStart.gif View Code
<% @ Application Language = " C# " %>

< script runat = " server " >

void Application_Start( object sender, EventArgs e)
{
// Code that runs on application startup
// 开启SqlDependency的监听
System.Data.SqlClient.SqlDependency.Start(System.Configuration.ConfigurationManager.ConnectionStrings[ " MsSqlNotification " ].ConnectionString);
}

void Application_End( object sender, EventArgs e)
{
// Code that runs on application shutdown
System.Data.SqlClient.SqlDependency.Stop(System.Configuration.ConfigurationManager.ConnectionStrings[ " MsSqlNotification " ].ConnectionString);
}

void Application_Error( object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs

}

void Session_Start( object sender, EventArgs e)
{
// Code that runs when a new session is started

}

void Session_End( object sender, EventArgs e)
{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.

}

</ script >

//DataCacheDemo/App_Code/noticeSqlDependency.aspx.aspx

ContractedBlock.gif ExpandedBlockStart.gif View Code
<% @ Page Language = " C# " AutoEventWireup = " true " CodeFile = " noticeSqlDependency.aspx.cs " Inherits = " noticeSqlDependency " %>

<! 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 runat ="server" >
< title ></ title >
</ head >
< body >
< form id ="form1" runat ="server" >
< span > 基于通知机制的SQL缓存依赖(Ms Sql Server): </ span >
< hr />
< asp:GridView ID ="grd_product" runat ="server" >
</ asp:GridView >
< hr />
< span > 基于通知机制的SQL缓存依赖(Oracle): </ span >
< hr />
< asp:GridView ID ="grd_region" runat ="server" >
</ asp:GridView >
</ form >
</ body >
</ html >

//DataCacheDemo/App_Code/noticeSqlDependency.aspx.aspx.cs

ContractedBlock.gif ExpandedBlockStart.gif View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class noticeSqlDependency : System.Web.UI.Page
{
protected void Page_Load( object sender, EventArgs e)
{
GetSqlData();
GetOracleData();
}

protected void GetSqlData()
{
// 1. 从缓存中读取数据
System.Data.DataTable dt = HttpContext.Current.Cache[ " product " ] as System.Data.DataTable;
if (dt == null )
{
// 2. 创建Sql缓存依赖对象
string constr = System.Configuration.ConfigurationManager.ConnectionStrings[ " MsSqlNotification " ].ConnectionString;
string sqlstr = " SELECT ProductId, CategoryId, Name, Descn, Image FROM dbo.Product " ; // 通知机制只支持最简单的Select语句
System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(constr);
System.Data.SqlClient.SqlCommand command
= new System.Data.SqlClient.SqlCommand(sqlstr, connection);
command.CommandType
= System.Data.CommandType.Text;
System.Web.Caching.SqlCacheDependency scd
= new System.Web.Caching.SqlCacheDependency(command); // 别忘了在Global.asax中开启SqlDependency侦听

System.Data.SqlClient.SqlDataAdapter sda
= new System.Data.SqlClient.SqlDataAdapter(command);
System.Data.DataSet ds
= new System.Data.DataSet();

// 3. 从数据库中读取
try
{
sda.Fill(ds);
dt
= ds.Tables[ 0 ];
// 4. 保存到缓存中
HttpContext.Current.Cache.Add( " product " , dt, scd, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, new System.Web.Caching.CacheItemRemovedCallback(CallbackMethod));
}
catch (System.Data.SqlClient.SqlException se)
{ }
}
this .grd_product.DataSource = dt;
this .grd_product.DataBind();
}

// 当被缓存的数据从缓存中移除时, 激发的事件. 缓存依赖的回调方法必须是静态方法, 实例方法会阻止垃圾回收.
private static void CallbackMethod( string key, object value, System.Web.Caching.CacheItemRemovedReason reason)
{
// 回调方法执行时, 可能根本不存在HttpContext对象, 这时应该是用HttpRuntime对象获得缓存的引用

}

protected void GetOracleData()
{
// 1. 从缓存读数据
System.Data.DataTable dt = HttpContext.Current.Cache[ " regions " ] as System.Data.DataTable;
if (dt == null )
{
// 2. 创建缓存依赖对象
System.Web.Caching.CacheDependency cd = new System.Web.Caching.CacheDependency( " c:\\orcltmp\\REGIONS.txt " );

// 3. 从数据库读数据
string constr = System.Configuration.ConfigurationManager.ConnectionStrings[ " Oracle " ].ConnectionString;
string sqlstr = " select * from regions " ;
Oracle.DataAccess.Client.OracleConnection connection
= new Oracle.DataAccess.Client.OracleConnection(constr);
Oracle.DataAccess.Client.OracleCommand command
= new Oracle.DataAccess.Client.OracleCommand(sqlstr, connection);
command.CommandType
= System.Data.CommandType.Text;

try
{
Oracle.DataAccess.Client.OracleDataAdapter oda
= new Oracle.DataAccess.Client.OracleDataAdapter(command);
System.Data.DataSet ds
= new System.Data.DataSet();
oda.Fill(ds);
dt
= ds.Tables[ 0 ];
HttpContext.Current.Cache.Add(
" regions " , dt, cd, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan( 0 , 5 , 0 ), System.Web.Caching.CacheItemPriority.Normal, new System.Web.Caching.CacheItemRemovedCallback(OracleCallback));
}
catch (Oracle.DataAccess.Client.OracleException oe)
{}
}
this .grd_region.DataSource = dt;
this .grd_region.DataBind();
}

protected static void OracleCallback( string key, object value, System.Web.Caching.CacheItemRemovedReason reason)
{
// 清空缓存
// HttpContext.Current.Cache.Remove("regions"); ---X, 此时不一定有HttpContext对象
HttpRuntime.Cache.Remove( " regions " );
}
}

差点忘了, 还有网站优化:

通常我们面对一个站时, 可以从以下几个方面考虑优化的问题:

a. Ajax, 使用Ajax技术提升客户体验

b. 浏览器缓存(客户端缓存, 缓存后替换)

c. 应用程序处理管道级别的缓存(整页级缓存, 含IIS位置的整页缓存)

d. 控件级缓存(用户控件中使用缓存技术)

e. 数据集缓存(效果较明显)

f. 代码级的优化

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
\contentsline {chapter}{Contents}{2}{section*.1} {1}Java基础}{17}{chapter.1} {1.1}基本语法}{17}{section.1.1} {1.2}数字表达方式}{17}{section.1.2} {1.3}补码}{19}{section.1.3} {1.3.1}总结}{23}{subsection.1.3.1} {1.4}数据类型}{23}{section.1.4} {1.4.1}整数与浮点数}{23}{subsection.1.4.1} {1.4.1.1}浮点数原理}{24}{subsubsection.1.4.1.1} {1.4.2}格式输出浮点数}{24}{subsection.1.4.2} {1.4.3}\texttt {char}}{24}{subsection.1.4.3} {1.4.4}转义字符}{25}{subsection.1.4.4} {1.4.5}Boolean 布尔值}{25}{subsection.1.4.5} {1.5}基本类型变量的初始值}{26}{section.1.5} {1.6}数据类型转换}{26}{section.1.6} {1.7}方法}{26}{section.1.7} {1.8}运算符}{27}{section.1.8} {1.8.1}自增运算}{28}{subsection.1.8.1} {1.8.1.1}Postincrement}{28}{subsubsection.1.8.1.1} {1.8.1.2}Preincrement}{28}{subsubsection.1.8.1.2} {1.8.1.3}复合赋值运算}{28}{subsubsection.1.8.1.3} {1.8.2}逻辑运算}{29}{subsection.1.8.2} {1.8.3}条件运算符}{29}{subsection.1.8.3} {1.8.4}移位运算符}{30}{subsection.1.8.4} {1.9}流程控制}{31}{section.1.9} {1.9.1}\texttt {if\ldots esle\ldots }}{31}{subsection.1.9.1} {1.9.2}\texttt {switch}}{31}{subsection.1.9.2} {1.9.3}\texttt {while}}{32}{subsection.1.9.3} {1.9.4}\texttt {for}}{32}{subsection.1.9.4} {1.9.5}foreach}{32}{subsection.1.9.5} {1.9.6}go-to}{33}{subsection.1.9.6} {1.9.7}\texttt {do-while}}{33}{subsection.1.9.7} {1.10}数组(array)}{34}{section.1.10} {1.10.1}数组变量的声明}{34}{subsection.1.10.1} {1.10.2}数组变量的初始}{34}{subsection.1.10.2} {1.10.3}数组对象的引用}{35}{subsection.1.10.3} {1.10.4}数组对象的复制}{35}{subsection.1.10.4} {1.10.5}扩充数组对象长度}{36}{subsection.1.10.5} {1.10.6}Problems}{37}{subsection.1.10.6} {1.11}简单算法}{38}{section.1.11} {1.11.1}打乱算法}{38}{subsection.1.11.1} {1.11.2}排序算法}{38}{subsection.1.11.2} {1.11.2.1}选择排序}{38}{subsubsection.1.11.2.1} {1.11.2.2}冒泡排序}{39}{subsubsection.1.11.2.2} {1.11.2.3}插入排序}{40}{subsubsection.1.11.2.3} {1.11.3}递归调用}{41}{subsection.1.11.3} {1.12}Java API}{41}{section.1.12} {1.13}Linux命令}{41}{section.1.13} {1.13.1}基本查看、移动}{41}{subsection.1.13.1} {1.13.2}权限}{42}{subsection.1.13.2} {1.13.3}打包备份与恢复}{42}{subsection.1.13.3} {1.13.3.1}\texttt {tar},\texttt {gzip}}{42}{subsubsection.1.13.3.1} {1.13.3.2}\texttt {zip}}{42}{subsubsection.1.13.3.2} {1.13.3.3}文本创建与编辑}{43}{subsubsection.1.13.3.3} {1.14}\texttt {PATH}}{43}{section.1.14} {1.14.1}Java的打包命令}{44}{subsection.1.14.1} {2}Everything is an Object }{45}{chapter.2} {2.1}类与对象}{45}{section.2.1} {2.1.1}构造方法}{45}{subsection.2.1.1} {2.1.2}Java变量类型}{47}{subsection.2.1.2} {2.1.3}面向对象的编程}{47}{subsection.2.1.3} {2.2}继承}{48}{section.2.2} {2.2.1}super(), this()}{49}{subsection.2.2.1} {2.2.2}方法重写/覆盖}{50}{subsection.2.2.2} {2.3}修饰符}{51}{section.2.3} {2.4}父类对象的方法调用}{51}{section.2.4} {2.5}封装}{52}{section.2.5} {2.6}多态}{53}{section.2.6} {2.7}Sample code}{54}{section.2.7} {2.8}框架中移动的小球}{59}{section.2.8} {2.9}抽象与接口}{59}{section.2.9} {2.10}访问控制}{60}{section.2.10} {2.10.1}类的属性}{60}{subsection.2.10.1} {2.10.2}类的方法}{61}{subsection.2.10.2} {2.10.3}静态代码块}{62}{subsection.2.10.3} {2.11}\ttfamily final}{63}{section.2.11} {2.12}\ttfamily abstract}{63}{section.2.12} {2.13}\ttfamily interface}{64}{section.2.13} {2.14}JavaBean规范}{66}{section.2.14} {3}常用类}{67}{chapter.3} {3.1}Object类}{67}{section.3.1} {3.1.1}\ttfamily toString}{67}{subsection.3.1.1} {3.1.2}\ttfamily equals}{67}{subsection.3.1.2} {3.1.3}\ttfamily hashCode}{68}{subsection.3.1.3} {3.2}String类}{69}{section.3.2} {3.3}String常量重利用}{70}{section.3.3} {3.4}正则表达式}{71}{section.3.4} {3.5}StringBuffer}{75}{section.3.5} {3.6}StringBuilder}{76}{section.3.6} {3.7}StringBuilder与StringBuffer的缺点}{76}{section.3.7} {3.8}内部类}{77}{section.3.8} {4}Collection}{80}{chapter.4} {4.1}\ttfamily java.util.ArrayList}{80}{section.4.1} {4.2}\ttfamily java.util.LinkedList}{81}{section.4.2} {4.3}贪吃蛇案例}{82}{section.4.3} {4.4}散列表与HashMap}{83}{section.4.4} {4.4.1}java.util.HashMap}{83}{subsection.4.4.1} {4.5}\ttfamily java.util.HashSet}{84}{section.4.5} {4.6}泛型}{84}{section.4.6} {4.7}集合的迭代(Iterator)}{85}{section.4.7} {4.8}Collections集合工具类}{86}{section.4.8} {4.9}Comparable与Comparator}{86}{section.4.9} {4.9.1}Comparable}{86}{subsection.4.9.1} {4.9.2}Comparator}{87}{subsection.4.9.2} {4.10}包装类}{87}{section.4.10} {4.11}集合的复制}{88}{section.4.11} {4.12}集合的同步}{89}{section.4.12} {4.13}集合转换为数组}{89}{section.4.13} {4.14}数组转换为集合}{89}{section.4.14} {4.15}Map的迭代}{90}{section.4.15} {4.15.1}字符统计}{91}{subsection.4.15.1} {5}格式输入输出}{94}{chapter.5} {5.1}时间与日期}{94}{section.5.1} {5.1.1}各类时间日期转换}{94}{subsection.5.1.1} {5.1.2}时间的输入与输出}{97}{subsection.5.1.2} {5.2}数字的输入输出}{97}{section.5.2} {5.2.1}将浮点数四舍五入到指定精度}{98}{subsection.5.2.1} {6}Exception}{99}{chapter.6} {6.1}\ttfamily try-catch}{99}{section.6.1} {6.2}\ttfamily finally}{100}{section.6.2} {6.3}\ttfamily throws}{101}{section.6.3} {7}IO}{103}{chapter.7} {7.1}Java的文件系统管理}{103}{section.7.1} {7.2}回调模式与FileFilter}{104}{section.7.2} {7.3}\ttfamily RandomAccessFile}{106}{section.7.3} {7.4}基本类型数据序列}{108}{section.7.4} {7.5}String的序列}{109}{section.7.5} {7.6}InputStream与OutputStream}{109}{section.7.6} {7.6.1}FileInputStream}{109}{subsection.7.6.1} {7.6.2}FileOutputStream}{110}{subsection.7.6.2} {7.7}流}{110}{section.7.7} {7.8}Buffer}{112}{section.7.8} {7.9}字符流}{112}{section.7.9} {7.10}缓冲字符输入输出流}{113}{section.7.10} {7.11}文件常用操作}{114}{section.7.11} {7.12}对象序列}{117}{section.7.12} {8}多线程}{121}{chapter.8} {8.1}线程的常用属性与方法}{121}{section.8.1} {8.2}后台线程}{123}{section.8.2} {8.3}创建线程的两种方法}{123}{section.8.3} {8.4}Runnable}{123}{section.8.4} {8.5}Sleep阻塞与打断唤醒}{124}{section.8.5} {8.5.1}sleep与wait的差异}{124}{subsection.8.5.1} {8.6}IO阻塞}{126}{section.8.6} {8.7}同步与异步}{126}{section.8.7} {8.8}Timer}{133}{section.8.8} {9}Java网络编程}{135}{chapter.9} {10}反射}{141}{chapter.10} {10.1}Class}{141}{section.10.1} {10.1.1}Field}{145}{subsection.10.1.1} {10.1.2}Method}{145}{subsection.10.1.2} {10.1.3}Constructor}{145}{subsection.10.1.3} {10.2}其他Java相关}{146}{section.10.2} {11}项目}{148}{chapter.11} {11.1}ELTS}{148}{section.11.1} {12}Oracle数据库}{151}{chapter.12} {12.1}术语}{151}{section.12.1} {12.2}登录数据库}{151}{section.12.2} {12.3}创建表格}{152}{section.12.3} {12.4}关于null值}{154}{section.12.4} {12.5}操作符与实例}{154}{section.12.5} {12.5.1}where}{154}{subsection.12.5.1} {12.6}函数}{156}{section.12.6} {12.7}组函数}{158}{section.12.7} {12.7.1}group by}{159}{subsection.12.7.1} {12.7.2}having}{160}{subsection.12.7.2} {12.8}子查询}{161}{section.12.8} {12.9} 授权与回收权限}{161}{section.12.9} {12.10}示例}{162}{section.12.10} {12.10.1}exists}{165}{subsection.12.10.1} {12.11}集合操作}{165}{section.12.11} {12.11.1}union}{166}{subsection.12.11.1} {12.11.2}intersect与minus}{166}{subsection.12.11.2} {12.11.3}join}{166}{subsection.12.11.3} {12.11.3.1}cross join}{166}{subsubsection.12.11.3.1} {12.11.3.2}inner join}{167}{subsubsection.12.11.3.2} {12.11.3.3}outer join}{170}{subsubsection.12.11.3.3} {12.11.3.4}full join}{172}{subsubsection.12.11.3.4} {12.12}inner join与outer join比较}{172}{section.12.12} {12.12.1}非等值连接}{174}{subsection.12.12.1} {12.13}DML语句}{175}{section.12.13} {12.13.1}insert}{175}{subsection.12.13.1} {12.13.2}create}{175}{subsection.12.13.2} {12.13.3}rownum}{175}{subsection.12.13.3} {12.13.4}update}{176}{subsection.12.13.4} {12.13.5}delete}{177}{subsection.12.13.5} {12.13.6}drop}{177}{subsection.12.13.6} {12.13.7}rename}{177}{subsection.12.13.7} {12.14}SQL脚本}{177}{section.12.14} {12.15}Transaction}{177}{section.12.15} {12.16}char与varchar2}{178}{section.12.16} {12.17}number}{179}{section.12.17} {12.18}\ttfamily user\_tables, user\_objects}{179}{section.12.18} {12.19}truncate}{179}{section.12.19} {12.20}alter}{180}{section.12.20} {12.21}constraint}{180}{section.12.21} {12.21.1}primary key, unique}{181}{subsection.12.21.1} {12.21.2}unique}{182}{subsection.12.21.2} {12.21.3}foreign key}{182}{subsection.12.21.3} {12.22}view}{187}{section.12.22} {12.23}index, rowid}{187}{section.12.23} {12.24}sequence}{189}{section.12.24} {12.25}PL/SQL}{189}{section.12.25} {13}JDBC}{191}{chapter.13} {13.1}forName}{191}{section.13.1} {13.2}JDBC}{191}{section.13.2} {13.3}连接Oracle数据库及操作}{192}{section.13.3} {13.4}批处理模式}{195}{section.13.4} {13.5}分页查询}{196}{section.13.5} {13.5.1}MySQL}{198}{subsection.13.5.1} {13.6}连接池}{199}{section.13.6} {13.6.1}Wrapper}{199}{subsection.13.6.1} {13.7}DAO}{199}{section.13.7} {13.8}java.util.Date与java.sql.Date比较}{200}{section.13.8} {13.9}Meta Data}{201}{section.13.9} {13.10}可滚动结果集}{201}{section.13.10} {13.11}Procedure}{201}{section.13.11} {14}xml}{204}{chapter.14} {14.1}元素}{204}{section.14.1} {14.2}XML的设计}{205}{section.14.2} {14.3}DTD/Schema}{205}{section.14.3} {14.3.1}SAX应用}{206}{subsection.14.3.1} {14.4}dom4j}{207}{section.14.4} {14.5}XPath}{210}{section.14.5} {14.6}apache.commons}{211}{section.14.6} {15}sqlite3}{213}{chapter.15} {16}Web基础}{215}{chapter.16} {16.1}HTML}{215}{section.16.1} {16.2}head区域}{215}{section.16.2} {16.3}body区域}{216}{section.16.3} {16.4}常用标记}{216}{section.16.4} {16.4.1}span, div}{216}{subsection.16.4.1} {16.4.2}a}{216}{subsection.16.4.2} {16.4.3}img}{216}{subsection.16.4.3} {16.4.4}table}{217}{subsection.16.4.4} {16.5}form}{220}{section.16.5} {16.5.1}form的元素}{220}{subsection.16.5.1} {16.6}列表}{221}{section.16.6} {16.7}select与option}{221}{section.16.7} {16.8}frame}{222}{section.16.8} {16.9}CSS}{224}{section.16.9} {16.10}Selector}{228}{section.16.10} {16.11}样式属性}{230}{section.16.11} {16.11.1}border}{230}{subsection.16.11.1} {16.11.2}display}{230}{subsection.16.11.2} {16.11.3}position}{230}{subsection.16.11.3} {16.11.4}z-index}{231}{subsection.16.11.4} {16.11.5}文本属性}{231}{subsection.16.11.5} {16.11.6}边距属性}{231}{subsection.16.11.6} {16.11.7}float}{232}{subsection.16.11.7} {16.11.8}list-style}{232}{subsection.16.11.8} {16.12}JavaScript}{232}{section.16.12} {16.12.1}JavaScript基本语法}{236}{subsection.16.12.1} {16.12.2}内置数据类型}{237}{subsection.16.12.2} {16.12.3}带参数的函数}{237}{subsection.16.12.3} {16.13}常用内置对象}{238}{section.16.13} {16.13.1}String}{238}{subsection.16.13.1} {16.13.2}Array}{239}{subsection.16.13.2} {16.13.3}Math}{239}{subsection.16.13.3} {16.13.4}Date}{240}{subsection.16.13.4} {16.13.5}Error}{240}{subsection.16.13.5} {16.13.6}Regex}{240}{subsection.16.13.6} {16.13.7}Function}{240}{subsection.16.13.7} {16.13.8}Date}{241}{subsection.16.13.8} {16.14}页内显示}{241}{section.16.14} {16.15}DOM}{243}{section.16.15} {16.15.1}查询节点}{243}{subsection.16.15.1} {16.15.2}获取节点信息}{243}{subsection.16.15.2} {16.15.3}修改节点信息}{244}{subsection.16.15.3} {16.15.4}添加新节点}{244}{subsection.16.15.4} {16.15.5}删除节点}{244}{subsection.16.15.5} {16.16}页签效果}{244}{section.16.16} {16.17}封装}{244}{section.16.17} {16.18}表格的动态创建}{245}{section.16.18} {16.19}BOM}{246}{section.16.19} {16.19.1}window}{246}{subsection.16.19.1} {16.19.1.1}open(url)}{246}{subsubsection.16.19.1.1} {16.19.1.2}focus}{246}{subsubsection.16.19.1.2} {16.19.1.3}confirm}{246}{subsubsection.16.19.1.3} {16.19.1.4}prompt}{247}{subsubsection.16.19.1.4} {16.19.1.5}setInterval}{247}{subsubsection.16.19.1.5} {16.19.1.6}clearInterval}{247}{subsubsection.16.19.1.6} {16.19.1.7}setTimeout}{247}{subsubsection.16.19.1.7} {16.19.1.8}clearTimeOut}{247}{subsubsection.16.19.1.8} {16.19.2}location}{247}{subsection.16.19.2} {16.19.3}screen}{248}{subsection.16.19.3} {16.19.4}navigator}{248}{subsection.16.19.4} {16.19.5}event对象}{248}{subsection.16.19.5} {16.19.5.1}事件位置}{250}{subsubsection.16.19.5.1} {16.19.6}history}{250}{subsection.16.19.6} {16.20}Object-Oriented Programming}{250}{section.16.20} {17}Servlet}{259}{chapter.17} {17.1}什么是Servlet}{259}{section.17.1} {17.2}如何写Servlet}{259}{section.17.2} {17.3}安装tomcat与简单使用}{260}{section.17.3} {17.3.1}常见错误}{262}{subsection.17.3.1} {17.3.2}示例}{263}{subsection.17.3.2} {17.4}Servlet引用的jar包}{266}{section.17.4} {17.5}HTTP协议}{266}{section.17.5} {17.6}表单处理}{267}{section.17.6} {17.7}表单中文乱码}{267}{section.17.7} {17.8}MySQL}{268}{section.17.8} {17.8.1}创建数据库}{268}{subsection.17.8.1} {17.8.2}克隆数据库}{268}{subsection.17.8.2} {17.8.3}查看数据库编码}{268}{subsection.17.8.3} {17.8.4}创建表格}{269}{subsection.17.8.4} {17.8.5}插入记录}{269}{subsection.17.8.5} {17.8.6}查询、修改、删除记录}{269}{subsection.17.8.6} {17.8.7}使用SQL脚本}{270}{subsection.17.8.7} {17.8.8}分行问题}{270}{subsection.17.8.8} {17.8.9}在Servlet中使用JDBC访问数据库}{271}{subsection.17.8.9} {17.8.10}连接数}{273}{subsection.17.8.10} {17.9}重定向}{273}{section.17.9} {17.10}DAO}{274}{section.17.10} {17.11}DAO工厂}{274}{section.17.11} {17.12}类加载器}{277}{section.17.12} {17.13}Servlet及数据库中文}{277}{section.17.13} {17.14}让servlet处理多种请求}{278}{section.17.14} {17.14.1}servlet容器如何处理请求资源路径?}{281}{subsection.17.14.1} {17.15}servlet的生命周期}{282}{section.17.15} {18}JSP}{284}{chapter.18} {18.1}JSP文件的写法}{284}{section.18.1} {18.2}JSP的执行步骤}{285}{section.18.2} {18.3}JSP文件的指令}{285}{section.18.3} {18.4}转发}{286}{section.18.4} {18.4.1}转发与重定向的差别}{287}{subsection.18.4.1} {18.5}处理异常}{288}{section.18.5} {18.6}注册登录页面}{288}{section.18.6} {18.7}加密数据库密码列}{288}{section.18.7} {18.8}路径问题}{289}{section.18.8} {18.8.1}绝对路径的使用}{290}{subsection.18.8.1} {18.9}状态管理}{291}{section.18.9} {18.9.1}cookie}{291}{subsection.18.9.1} {18.9.1.1}cookie的编码}{291}{subsubsection.18.9.1.1} {18.9.1.2}cookie的生存时间}{292}{subsubsection.18.9.1.2} {18.9.1.3}cookie的路径问题}{292}{subsubsection.18.9.1.3} {18.9.1.4}cookie的限制}{293}{subsubsection.18.9.1.4} {18.9.2}session}{294}{subsection.18.9.2} {18.9.2.1}获取session}{294}{subsubsection.18.9.2.1} {18.9.2.2}session的方法}{295}{subsubsection.18.9.2.2} {18.9.2.3}session的超时}{296}{subsubsection.18.9.2.3} {18.9.2.4}删除session}{296}{subsubsection.18.9.2.4} {18.9.2.5}session验证}{297}{subsubsection.18.9.2.5} {18.10}购物车案例}{300}{section.18.10} {18.11}URL重写}{301}{section.18.11} {18.12}session的优缺点}{302}{section.18.12} {18.13}过滤器}{302}{section.18.13} {18.14}监听器}{303}{section.18.14} {18.15}ServletContext接口}{303}{section.18.15} {18.16}上传文件}{304}{section.18.16} {18.17}Servlet线程安全问题}{308}{section.18.17} {18.18}el表达式}{309}{section.18.18} {18.18.1}第一种方式}{310}{subsection.18.18.1} {18.18.2}第二种方式}{310}{subsection.18.18.2} {18.18.3}获取请求参数的值}{311}{subsection.18.18.3} {18.18.4}简单计算及输出等}{311}{subsection.18.18.4} {18.19}JSP标签}{311}{section.18.19} {18.19.1}JSTL}{312}{subsection.18.19.1} {18.19.2}自定义标签}{312}{subsection.18.19.2} {18.19.3}在JavaEE5及以上版本,如何使用el表达式与标准标签}{316}{subsection.18.19.3} {18.20}MVC}{317}{section.18.20} {18.20.1}在web开发中如何使用MVC}{318}{subsection.18.20.1} {18.20.2}MVC的特殊应用}{318}{subsection.18.20.2} {19}Ajax}{319}{chapter.19} {19.1}Ajax对象的属性}{319}{section.19.1} {19.2}编程}{320}{section.19.2} {19.3}Ajax中文处理}{321}{section.19.3} {19.3.1}链接地址包含中文}{321}{subsection.19.3.1} {19.3.2}链接地址包含中文参数值}{321}{subsection.19.3.2} {19.3.3}Ajax中的编码问题}{321}{subsection.19.3.3} {19.4}以post方式发送请求}{322}{section.19.4} {19.4.1}post请求时的中文编码}{322}{subsection.19.4.1} {19.5}Ajax级联下拉菜单示例}{322}{section.19.5} {19.6}Ajax的优点}{329}{section.19.6} {20}Json}{330}{chapter.20} {20.1}Json的语法}{330}{section.20.1} {20.2}在Ajax应用中使用Json}{330}{section.20.2} {20.2.1}Json字符串转换为JavaScript对象}{331}{subsection.20.2.1} {20.3}缓存问题}{334}{section.20.3} {21}jQuery}{335}{chapter.21} {21.1}使用jQuery}{335}{section.21.1} {21.2}jQuery对象与DOM对象的转换}{335}{section.21.2} {21.3}选择器}{336}{section.21.3} {21.4}DOM操作}{337}{section.21.4} {21.4.1}查询与修改}{337}{subsection.21.4.1} {21.4.2}创建}{338}{subsection.21.4.2} {21.4.3}插入删除节点}{338}{subsection.21.4.3} {21.4.4}复制节点}{339}{subsection.21.4.4} {21.4.5}属性操作}{339}{subsection.21.4.5} {21.4.6}样式操作}{339}{subsection.21.4.6} {21.4.7}遍历节点}{340}{subsection.21.4.7} {21.4.8}模拟操作}{341}{subsection.21.4.8} {21.5}事件处理}{344}{section.21.5} {21.5.1}事件}{345}{subsection.21.5.1} {21.5.2}事件冒泡}{346}{subsection.21.5.2} {21.5.3}jQuery事件对象属性}{346}{subsection.21.5.3} {21.6}动画}{347}{section.21.6} {21.7}类数组}{348}{section.21.7} {21.8}jQuery对Ajax开发的支持}{348}{section.21.8} {21.8.1}get, post}{349}{subsection.21.8.1} {21.8.2}.ajax}{350}{subsection.21.8.2} {21.9}Debugging jQuery}{351}{section.21.9} {22}struts2}{352}{chapter.22} {22.1}准备strut2开发类库}{352}{section.22.1} {22.2}struts配置}{354}{section.22.2} {22.3}安全路径}{354}{section.22.3} {22.4}用户访问}{355}{section.22.4} {22.5}访问数据库}{355}{section.22.5} {22.5.1}数据分页}{355}{subsection.22.5.1} {22.6}struts2分页查询、显示}{355}{section.22.6} {22.7}Ognl语言}{357}{section.22.7} {22.7.1}Ognl中的运算}{358}{subsection.22.7.1} {22.7.2}Ognl调用普通方法}{358}{subsection.22.7.2} {22.7.3}Ognl调用静态方法}{358}{subsection.22.7.3} {22.7.4}创建List}{358}{subsection.22.7.4} {22.7.5}创建Map}{359}{subsection.22.7.5} {22.7.6}投影}{359}{subsection.22.7.6} {22.7.7}选择性获取元素集合}{359}{subsection.22.7.7} {22.7.8}Ognl操作对象}{359}{subsection.22.7.8} {22.7.9}Struts2的Ognl}{360}{subsection.22.7.9} {22.8}Struts2标签}{360}{section.22.8} {22.8.1}数据提交}{361}{subsection.22.8.1} {22.8.2}测试对象是否为空}{362}{subsection.22.8.2} {22.8.3}获取checkbox项数据}{362}{subsection.22.8.3} {22.9}JUnit Test}{362}{section.22.9} {22.9.1}JUnit注释}{363}{subsection.22.9.1} {22.9.2}Debug Mode}{363}{subsection.22.9.2} {22.10}使用JavaScript提交表单}{364}{section.22.10} {22.11}使用JavaScript提交action请求}{365}{section.22.11} {22.12}Struts2对象创建模式}{366}{section.22.12} {22.13}获取session}{366}{section.22.13} {22.14}属性注入}{367}{section.22.14} {22.15}ActionSupport}{367}{section.22.15} {22.16}默认action}{368}{section.22.16} {22.17}struts2执行流程}{368}{section.22.17} {22.18}常用result类型}{370}{section.22.18} {22.18.1}Struts2验证码}{372}{subsection.22.18.1} {22.19}Json插件}{374}{section.22.19} {22.20}Struts2动态action用法}{376}{section.22.20} {22.21}reset}{376}{section.22.21} {22.22}注解action}{377}{section.22.22} {22.23}More tags}{377}{section.22.23} {22.23.1}form, checkbox}{377}{subsection.22.23.1} {22.23.2}checkboxlist}{377}{subsection.22.23.2} {22.23.3}radio}{378}{subsection.22.23.3} {22.23.4}select}{378}{subsection.22.23.4} {22.23.5}使用服务器数据显示列表}{378}{subsection.22.23.5} {22.24}interceptor}{379}{section.22.24} {22.24.1}interceptor-stack}{381}{subsection.22.24.1} {22.24.2}默认拦截器}{382}{subsection.22.24.2} {22.24.3}引用父类拦截器}{383}{subsection.22.24.3} {22.25}struts安全验证}{383}{section.22.25} {22.26}struts2上传}{384}{section.22.26} {22.27}struts2国际}{385}{section.22.27} {23}当当网项目}{386}{chapter.23} {23.1}struts2常量}{389}{section.23.1} {23.2}java.util.UUID}{390}{section.23.2} {23.3}获取IP地址}{390}{section.23.3} {23.4}动态嵌入另一页面}{390}{section.23.4} {23.5}jQuery.validate}{392}{section.23.5} {23.6}JSP页面布尔值判断}{395}{section.23.6} {23.7}创建产品与图书的数据库表格}{395}{section.23.7} {23.8}使用SSH重构的问题}{395}{section.23.8} {24}Hibernate}{398}{chapter.24} {24.1}ORM}{398}{section.24.1} {24.2}使用Hibernate}{399}{section.24.2} {24.3}表格创建}{400}{section.24.3} {24.4}获取Session}{401}{section.24.4} {24.5}hibernate事务}{402}{section.24.5} {24.6}查询}{402}{section.24.6} {24.7}主键生成策略(generator)}{403}{section.24.7} {24.8}默认值}{404}{section.24.8} {24.9}hibernate bean对象的生命周期}{404}{section.24.9} {24.9.1}数据同步}{405}{subsection.24.9.1} {24.10}Hibernate类型}{406}{section.24.10} {24.11}Hibernate懒加载}{407}{section.24.11} {24.11.1}懒加载原理}{408}{subsection.24.11.1} {24.11.2}使用懒加载}{408}{subsection.24.11.2} {24.11.3}在Struts2中应用懒加载机制}{409}{subsection.24.11.3} {24.11.4}使用Hibernate维护单对象session}{412}{subsection.24.11.4} {24.12}ORM}{412}{section.24.12} {24.12.1}many-to-one}{413}{subsection.24.12.1} {24.12.2}one-to-many}{413}{subsection.24.12.2} {24.12.3}many-to-many}{414}{subsection.24.12.3} {24.12.4}双向关联映射}{416}{subsection.24.12.4} {24.12.5}关系表}{417}{subsection.24.12.5} {24.12.6}Hibernate继承关系}{418}{subsection.24.12.6} {24.12.7}Hibernate组件映射}{419}{subsection.24.12.7} {24.13}HQL语句}{420}{section.24.13} {24.14}QBC语句}{422}{section.24.14} {24.15}使用SQL语句}{422}{section.24.15} {24.16}Hibernate缓存}{423}{section.24.16} {24.16.1}一级缓存}{423}{subsection.24.16.1} {24.16.1.1}批处理}{424}{subsubsection.24.16.1.1} {24.16.2}二级缓存}{424}{subsection.24.16.2} {24.16.3}查询缓存}{427}{subsection.24.16.3} {24.17}Hibernate锁机制}{428}{section.24.17} {24.17.1}悲观锁}{428}{subsection.24.17.1} {24.17.2}乐观锁}{429}{subsection.24.17.2} {24.18}Ant及Maven}{429}{section.24.18} {24.19}Hibernate注解}{429}{section.24.19} {25}Spring}{430}{chapter.25} {25.1}概念}{430}{section.25.1} {25.2}Spring开发}{431}{section.25.2} {25.2.1}依赖注入}{431}{subsection.25.2.1} {25.2.2}集合注入}{433}{subsection.25.2.2} {25.3}log4j}{434}{section.25.3} {25.4}Spring容器}{435}{section.25.4} {25.5}Spring容器对Bean对象的管理}{436}{section.25.5} {25.5.1}lazy-init}{436}{subsection.25.5.1} {25.5.2}Bean对象的初始与销毁}{437}{subsection.25.5.2} {25.6}AOP与代理模式}{437}{section.25.6} {25.6.1}动态代理模式}{438}{subsection.25.6.1} {25.6.2}Spring代理模式}{440}{subsection.25.6.2} {25.6.2.1}第一种情况}{440}{subsubsection.25.6.2.1} {25.6.2.2}第二种情况}{441}{subsubsection.25.6.2.2} {25.6.2.3}第三种情况:使用schema配置}{443}{subsubsection.25.6.2.3} {25.7}单例模式及Bean的作用域}{445}{section.25.7} {25.8}Spring JDBC}{446}{section.25.8} {25.9}Spring与Struts2集成}{448}{section.25.9} {25.10}Struts2, Spring, Hibernate}{450}{section.25.10} {25.10.1}spring-test: 使用注解方式测试}{455}{subsection.25.10.1} {25.11}Spring管理Hibernate}{456}{section.25.11} {25.12}分层管理Spring配置文件}{462}{section.25.12} {25.13}Spring中的Hibernate懒加载}{462}{section.25.13} {25.14}Spring中文过滤器}{463}{section.25.14} {25.15}Spring读取属性(.properties)文件}{464}{section.25.15} {25.16}Spring中的Hibernate数据库操作}{465}{section.25.16} {25.17}分页查询}{465}{section.25.17} \contentsline {chapter}{Todo list}{478}{lstnumber.-637.8} {A}T-GWAP}{480}{appendix.A} {A.1}PO}{480}{section.A.1} {A.2}DAO}{480}{section.A.2} {A.2.1}使用连接池}{480}{subsection.A.2.1} {A.3}BO}{485}{section.A.3} {A.3.1}ThreadLocal}{486}{subsection.A.3.1} {A.4}FC}{486}{section.A.4} {A.5}View}{486}{section.A.5} {A.6}框架}{486}{section.A.6} {A.6.1}简单工厂}{486}{subsection.A.6.1} {B}问题}{489}{appendix.B} \contentsline {chapter}{Index}{491}{section*.9} {B.0.2},}{491}{subsection.B.0.2}

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值