ASP生成静态网页技术的实现-最新文档
- 格式:doc
- 大小:23.00 KB
- 文档页数:6
动态改为静态页面的3个方法最后将动态该为静态页面的方法我给出来:.net中生成静态页面最简单的3种方法,注意要引用2个命名空间:using ;using system.io;first:在服务器上指定aspx网页,生成html静态页public partial class Default2 : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e){if (!IsPostBack){StreamWriter sw = new StreamWriter(Server.MapPath("静态页1.htm"), false, System.Text.Encoding.GetEncoding("gb2312"));Server.Execute("Default3.aspx", sw);sw.Close();}}}second:在服务器上执行aspx网页时在page_render事件里将本页面生成html静态页public partial class Default3 : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e){}protected override void Render(HtmlTextWriter writer){StringWriter html = new StringWriter();System.Web.UI.HtmlTextWriter tw = new System.Web.UI.HtmlTextWriter(html);base.Render(tw);System.IO.StreamWriter sw;sw = new System.IO.StreamWriter(Server.MapPath("静态页2.htm"), false, System.Text.Encoding.Default);sw.Write(html.ToString());sw.Close();tw.Close();Response.Write(html.ToString());}}third:从指定连接获取源代码生成html静态页public partial class Default4 : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e){if (!IsPostBack){string pageurl = "";WebRequest request = WebRequest.Create(pageurl);WebResponse response = request.GetResponse();Stream resstream = response.GetResponseStream();StreamReader sr = new StreamReader(resstream,System.Text.Encoding.Default);string contenthtml = sr.ReadToEnd();resstream.Close();sr.Close(); //写入文件System.IO.StreamWriter sw;sw = new System.IO.StreamWriter(Server.MapPath("静态页生成方法3.htm"), false, System.Text.Encoding.Default);sw.Write(contenthtml);sw.Close();} }}。
aspx页面生成静态的HTML页面的三种方法asp教程x页面生成静态的HTML页面的三种方法教程系统中,有些动态的页面常被频繁,如我们的首页index.aspx它涉及到大量的数据库教程查询工作,当不断有用户它时,服务器便不断向数据库的查询,实际上做了许多重复的工作服务器端的myPage.aspx客户端显示myPage.htm客户端针对这种资源的浪费情况,我们现在来设计一个解决方案。
我们先将那些一段时间内内容不会有什么改变,但又遭大量的动态页面生成静态的页面存放在服务器上,当客户端发出请求时,就让他们直接我们生成的静态页面,过程如下图。
客户端显示myPage.htm客户端Execute服务器端的myPage.aspx服务器端的myPage.htm现在我们需要一个后台程序来完成这些事情。
我们可将此做成一个类classAspxT oHtml ,其代码using System;using System.IO;using System.Web.UI;namespace LeoLu{/// summary/// AspxToHtml 的摘要说明。
/// /summarypublic class AspxT oHtml{/// summary/// Aspx文件url/// /summarypublic string strUrl;/// summary/// 生成html文件的保存路径/// /summarypublic string strSavePath;/// summary/// 生成html文件的文件名/// /summarypublic string strSaveFile;public AspxToHtml(){//// TOD 在此处添加构造函数逻辑//}/// summary/// 将strUrl放到strSavePath目录下,保存为strSaveFile/// /summary/// returns是否成功/returnspublic bool ExecAspxToHtml(){try{StringWriter strHTML = new StringWriter();System.Web.UI.Page myPage = new Page(); //System.Web.UI.Page中有个Server对象,我们要利用一下它myPage.Server.Execute(strUrl,strHTML);//将asp_net.aspx将在客户段显示的html内容读到了strHTML中StreamWriter sw = new StreamWriter(strSavePath+strSaveFile,true,System.Text.Encoding.GetEncoding("GB23 12"));//新建一个文件Test.htm,文件格式为GB2312sw.Write(strHTML.ToString()); //将strHTML中的字符写到Test.htm中strHTML.Close();//关闭StringWritersw.Close();//关闭StreamWriterreturn true;}catch{return false;}}/// summary/// 将Url放到Path目录下,保存为FileName/// /summary/// param name="Url"aspx页面url/param/// param name="Path"生成html文件的保存路径/param/// param name="FileName"生成html 文件的文件名/param/// returns/returnspublic bool ExecAspxToHtml(string Url,string Path,string FileName){try{StringWriter strHTML = new StringWriter();System.Web.UI.Page myPage = new Page(); //System.Web.UI.Page中有个Server对象,我们要利用一下它myPage.Server.Execute(Url,strHTML); //将asp_net.aspx将在客户段显示的html内容读到了strHTML中StreamWriter sw = new StreamWriter(Path+FileName,true,System.Text.Encoding.GetEncoding("GB23 12"));//新建一个文件Test.htm,文件格式为GB2312sw.Write(strHTML.ToString()); //将strHTML中的字符写到Test.htm中strHTML.Close();//关闭StringWritersw.Close();//关闭StreamWriterreturn true;}catch{return false;}}}}方法A:using System;using System.Data;using System.Configuration;using System.Collections;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;usingSystem.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;using System.IO;public partial class _Default : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e){Response.Write(AspxToHtml("./admin /Default2.aspx",Server.MapPath("./index.html")));}/// <summary>/// 将Url放到Path目录下,保存为FileName/// </summary>/// <param name="Url">aspx页面url</param>/// <param name="PathFileName">保存路径和生成html文件名</param> /// <returns></returns>public bool AspxToHtml(string Url, string PathFileName){try{StringWriter strHTML = new StringWriter();System.Web.UI.Page myPage = new Page();//System.Web.UI.Page中有个Server对象,我们要利用一下它myPage.Server.Execute(Url, strHTML);//将asp_net.aspx将在客户段显示的html内容读到了strHTML中//StreamWriter sw = new StreamWriter(PathFileName, false, System.Text.Encoding.GetEncoding("GB23 12"));StreamWriter sw = new StreamWriter(PathFileName, false,System.Text.Encoding.Default);sw.Write(strHTML.ToString());//将strHTML中的字符写到指定的文件中strHTML.Close();strHTML.Dispose();sw.Close();sw.Dispose();return true;}catch{return false;}}}方法B:using System;using System.Data;using System.Configuration;using System.Collections;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;usingSystem.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;public partial class _Default : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e){Label1.Text = DateTime.Now.ToString();}protected override void Render(HtmlTextWriter writer){System.IO.StringWriter html = new System.IO.StringWriter();System.Web.UI.HtmlTextWriter tw = new System.Web.UI.HtmlTextWriter(html);base.Render(tw);System.IO.StreamWriter sw;sw = new System.IO.StreamWriter(Server.MapPath(" Default.htm"), false, System.Text.Encoding.Default);sw.Write(html.ToString());sw.Close();tw.Close();Response.Write(html.ToString());}}。
ASP生成静态Html网页的几种方法网页生成静态Html文件有许多好处,比如生成html网页有利于被搜索引擎收录,不仅被收录的快还收录的全.前台脱离了数据访问,减轻对数据库访问的压力,加快网页打开速度. 所以吟清最近对生成html比较感兴趣,看了不少文章,也有一点点收获.1,下面这个例子直接利用FSO把html代码写入到文件中然后生成.html格式的文件<%filename="test.htm"if request("body")<>"" thenset fso = Server.CreateObject("Scripting.FileSystemObject") set htmlwrite = fso.CreateTextFile(server.mappath(""&filename&"")) htmlwrite.write "<html><head><title>" & request.form("title") & "</title></head>"htmlwrite.write "<body>输出Title内容: " & request.form("title") & "<br /> 输出Body内容:" & request.form("body")& "</body></html>"htmlwrite.closeset fout=nothingset fso=nothingend if%><form name="form" method="post" action=""><input name="title" value="Title" size=26><br><textarea name="body">Body</textarea><br><br><input type="submit" name="Submit" value="生成html"> </form>2、但是按照上面的方法生成html文件非常不方便,第二种方法就是利用模板技术,将模板中特殊代码的值替换为从表单或是数据库字段中接受过来的值,完成模板功能;将最终替换过的所有模板代码生成HTML文件.这种技术采用得比较多,大部分的CMS都是使用这类方法.template.htm ' //模板文件<html><head><title>$title$ by </title></head><body>$body$</body></html> ?TestTemplate.asp '// 生成Html <%Dim fso,htmlwriteDim strTitle,strContent,strOut'// 创建文件系统对象Set fso=Server.CreateObject("Scripting.FileSystemObject") '// 打开网页模板文件,读取模板内容Sethtmlwrite=fso.OpenTextFile(Server.MapPath("Template.htm")) strOut=f.ReadAllhtmlwrite.closestrTitle="生成的网页标题"strC'// 用真实内容替换模板中的标记strOut=Replace(strOut,"$title$",strTitle)strOut=Replace(strOut,"$body$",strContent)'// 创建要生成的静态页Sethtmlwrite=fso.CreateTextFile(Server.MapPath("test.htm"),true) '// 写入网页内容htmlwrite.WriteLine strOuthtmlwrite.closeResponse.Write "生成静态页成功!"'// 释放文件系统对象set htmlwrite=Nothingset fso=Nothing%>3、第三种方法就是用XMLHTTP获取动态页生成的HTML内容,再用ADODB.Stream或者Scripting.FileSystemObject保存成html 文件。
生成静态页面实现方法Posted on 2006-08-19 22:56 hongwei 阅读(1295) 评论(1)编辑收藏<!--Main.Aspx--><%@ page language="C#" %><%@ import namespace=System.IO %><script runat="server">protected override void OnInit (EventArgs e){int id;try{id = int.Parse (Request.QueryString["id"]);}catch{throw (new Exception ("页面没有指定id"));}string filename=Server.MapPath("statichtml_"+id+".html");//尝试读取已有文件Stream s = GetFileStream (filename);if (s != null)//如果文件存在并且读取成功{using (s){Stream2Stream (s, Response.OutputStream);Response.End ();}}//调用Main_Execute,并且获取其输出StringWriter sw = new StringWriter ();Server.Execute ("Main_Execute.aspx", sw);string content = sw.ToString ();//输出到客户端Response.Write(content);Response.Flush();--------------------------可以编辑的精品文档,你值得拥有,下载后想怎么改就怎么改---------------------------//写进文件try{using (FileStream fs = new FileStream (filename, FileMode.Create, FileAccess.Write, FileShare.Write)){using (StreamWriter streamwriter = new StreamWriter (fs, Response.ContentEnc oding)){streamwriter.Write (content);}}}finally{//Response.End ();}}static public void Stream2Stream (Stream src, Stream dst){byte[] buf = new byte[4096];while (true){int c = src.Read (buf, 0, buf.Length);if(c==0)return;dst.Write (buf, 0, c);}}public Stream GetFileStream(string filename){try{DateTime dt = File.GetLastWriteTime (filename);TimeSpan ts=dt - DateTime.Now;if(ts.TotalHours>1)return null;//1小时后过期return new FileStream (filename, FileMode.Open, FileAccess.Read, FileShare.Read);}catch{--------------------------可以编辑的精品文档,你值得拥有,下载后想怎么改就怎么改---------------------------return null;}}</script><!--Main_Execute.aspx--><%@ page language="C#" %><html><head runat="server"><title>Untitled Page</title></head><body>ID:<%=Request.QueryString["id"]%></body></html>其中原理是这样的.Main_Execute.aspx是生成HTML的页面.现在用Main.aspx来对它进行缓存.过程如下:首先根据页面参数算出文件名.(这个例子只根据Request.QueryString["id"]来算)尝试读取缓存的文件.如果成功,那么Response.End();如果不成功:使用Server.Execute来调用Main_Execute.aspx,并且获取它的结果内容.得到内容后,立刻输出到客户端.最后把内容写进文件里,提供给下一次做为缓存度取.--------------------------可以编辑的精品文档,你值得拥有,下载后想怎么改就怎么改---------------------------。
静态页面生成原理及实际应用技巧(大量数据时提高访问速度)2010-09-23 09:19:08| 分类:C#学习|字号订阅随着互联网的发展,B/S结构的程序开发已经占据了当今软件开发非常大的比重。
由于现在web程序的高访问量、大数据量、高效的用户体验效果等的要求,使静态页技术在越来越多的网站上得到了应用。
使用静态页面有如下好处:1、安全:使用静态页面,用户访问的使没有任何操作功能的html页面,可以说从安全性方面大大提高了程序及服务器的安全。
2、快速:用户访问的是提前生成好的静态页面,使用户对页面的请求瓶颈只受IO 的限制而不会有其他方面的影响。
3、降低服务器,数据库负载:因为用户访问的是静态页,对承载静态页的服务器配置要求降低了许多,同时,不会因为过大的访问量,造成数据库服务器负载过重等问题。
鉴于以上种种优势,好多新闻性的网站都采用了静态页面生成技术,下面就让我来个大家介绍一个用生成静态页面的方法。
在介绍生成方法之前,我们要考虑一个问题。
在中的服务器控件的代码是什么样的呢?源代码如下所示:<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label><asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><asp:Button ID="Button1" runat="server" Text="Button" />而以上的代码我们在通过浏览器访问后的代码是什么样呢?<span id="Label1">Label</span><input name="TextBox1" type="text" id="TextBox1" /><input type="submit" name="Button1" value="Button" id="Button1" />通过对比我们可以看出,服务器控件被浏览器访问时已经变成了浏览器可以识别的html代码。
Asp伪静态的实现及URL重写用ISAPI_Rewrite实现asp的静态化ASP网站程序在国内运用很广,但是类似于im286.asp?id=20050307213811这样的URL有点不利于搜索引擎的收录,也就是说不符合友好URL(URLs-Friendly)的标准,那么我们用ISAPI_Rewrite打造一个Clean URL,1.下载ISAPI_Rewrite.ISAPI_Rewrite分精简(Lite)和完全(Full)版.精简版不支持对每个虚拟主机站点进行重写,只能进行全局处理.不过对于有服务器的朋友,精简版也就够啦.精简版下载地址:/download/,就是那Lite Version (free)啦.2.安装.msi的文件,和装一般程序一样装就可以了,俺就装在D:\ISAPI_Rewrite.3.接下来一步比较重要哦,看仔细喽.打开Internet 信息服务,右键,web站点属性,电ISAPI筛选器选项卡.添加筛选器,名称自己填,路径自己指定ISAPI_Rewrite.dll,然后确定.4.来测试一下.新建一个1ting.asp,里面写上<%=request.querystring("inso")%>,效果就是执行的时候1ting.asp?inso=*浏览器显示*.5.这一步很重要哦,开始添加rewrite规则.正则,好头痛,幸亏这个例子比较简单.找到ISAPI_Rewrite目录,把httpd.ini的只读属性去掉,打开编辑.我们要把1ting.asp?inso=im286映射成为1ting-im286.html这样的类型,需要在httpd.ini里加上这么一行:RewriteRule /1ting-([0-9,a-z]*).html /1ting.asp\?inso=$1,保存.6.来来来,到浏览器里查看一下效果吧.输入http://127.0.0.1/1ting.asp?inso=im286和http://127.0.0.1/1ting-im286.html,显示的内容是不是都是im286?这就证明成功啦!嘿嘿,1ting-im286.html这样的页面要比1ting.asp?inso=im286容易收入,所以现在还在用动态方式的朋友可以尝试一下这样的静态映射效果. IIS Rewrite也可以实现这样的功能。
ASP动态网页静态化的实现: At present, most of the sites use dynamic web technology. This paper analysed application situation of the static and dynamic WEB technology in WEB site, summarized advantages and disadvantages of static web technology and dynamic web technology and proposed to staticize dynamic pages, in order to improve the efficiency of dynamic web. This paper describes the method of realizing the static page.1静态网页与动态网页技术静态网页是指网站的网页内容固定不变。
当用户浏览器通过互联网的HTTP向Web服务器请求提供网页内容时,服务器直接将静态HTML文档传输给用户浏览器,不需要任何代码解析。
现实中最常见的静态网页是以“.html”和“.htm”为扩展名的文件。
动态网页是指页面内容可以实现交互。
服务器会根据用户的要求和选择动态改变和响应,浏览用户可以及时得到服务器的反馈信息。
静态页面的优点是不需要服务器执行ASP、PHP、JSP或ASP等程序。
直接将页面代码传输给浏览客户端。
大大提高了页面显示速度。
相对于动态页面,静态页面的缺点是静态页面不易维护。
为了不断更新站点内容,必须不断重复制作HTML文档。
随着网站内容和信息量的日益扩增,大大增加了维护成本。
随着动态Web技术的飞速发展,动态交互站点成为了当今站点的主流页面形式。
但是,从另一个角度考虑,随着大型站点的推出,因其信息内容多,站点访问量大的原因,造成服务器的超负荷运转。
关于asp程序生成静态页(asp转html)--------------------------------------------------------------------------------网上这类的文章很多,大多数都是转载的,无非是两种:第一种:利用模板生成html文件;第二种:利用xmlhttp访问目标程序并保存成html第一种的麻烦之处在于要制作模板,做大型项目还好,小项目的话,灵活性就不足了;第二种有一个很大的缺陷:生成的静态页里的链接还是指向asp程序页面,光生成首页还好,要做到整站的话,麻烦更大;我使用的是第二种方法,不过,我加了链接的替换,使生成的html页面保持互通。
程序如下:<%server. script timeout=300'on error resume nextdim asp2html_langasp2html_lang="gb2312"function asp2html_cpath(str) '过滤路径str=replace(str,"\","")str=replace(str,":","")str=replace(str,"*","")str=replace(str,"?","")str=replace(str,"<","")str=replace(str,">","")str=replace(str,"|","")str=replace(str,chr(34),"")str=replace(str,"//","/")asp2html_cpath=strend functionfunction asp2html_b2s(str) '转换二进制数据为文本dim ostreamset ostream=server.createobject("adodb.stream")ostream.type=1ostream.mode=3ostream.openostream.write strostream.position=0ostream.type=2ostream.charset=asp2html_langasp2html_b2s=ostream.readtextostream.closeset ostream=nothingend functionfunction asp2html_gettag(str) '获取所有链接dim r,matches,match,tmpurl,start,overstart="<a"over=">"set r=new regexpr.ignorecase=truer.global=truer.pattern=""&start&".+?"&over&""set matches=r.execute(lcase(str))set r=nothingstart=replace(start,"\","")over=replace(over,"\","")for each match in matchestmpurl=split(trim(replace(replace(lcase(match.value),"<a",""),">","")),"href=")( 1)if instr(tmpurl," ")>0 thentmpurl=split(tmpurl," ")(0)end ifif instr(tmpurl,chr(34))>0 thentmpurl=replace(tmpurl,chr(34),"",1,1)tmpurl=split(tmpurl,chr(34))(0)end ifif instr(tmpurl,chr(34)&"+")<1 and instr(tmpurl,"+"&chr(34))<1 and instr(tmpurl,"'+")<1 and instr(tmpurl,"+'")<1 and instr(tmpurl,"java script :")<1 thentmpurl=replace(replace(tmpurl,chr(34),""),"'","")if instr(asp2html_gettag,"|"&tmpurl)<1 and tmpurl<>"#" thenasp2html_gettag=asp2html_gettag&"|"&tmpurlend ifend ifnextif asp2html_gettag<>"" thenasp2html_gettag=replace(asp2html_gettag,"|","",1,1)end ifend functionfunction asp2html_chgtag(str,path,surl) '替换链接为静态链接dim r,iurl,turliurl=replace(path,"?","\?")iurl=replace(iurl,"+","\+")iurl=replace(iurl,"$","\$")turl=pathif left(turl,1)="?" thenturl=surl&turlend ifset r=new regexpr.ignorecase=truer.global=truer.pattern="(<a.*)(""| |'|=)"&iurl&"(""| |'|>)(.*>)"asp2html_chgtag=r.replace(str,"$1$2"&asp2html_chgurl(turl)&"$3$4")set r=nothingend functionfunction asp2html_chgurl(str) '转换动态链接为静态链接dim tmpurltmpurl=lcase(str)if left(tmpurl,7)="http://" and instr(tmpurl,lcase(request.servervariables("server_name")))<1 thenasp2html_chgurl=tmpurlelseif instr(tmpurl,".asp")>0 and right(tmpurl,4)<>".htm" thentmpurl=replace(tmpurl,"?","-")tmpurl=replace(tmpurl,"&","$")tmpurl=replace(tmpurl,"=","--")if instr(tmpurl,"#")<1 thentmpurl=tmpurl&".htm"elsetmpurl=split(tmpurl,"#")(0)&".htm#"&split(tmpurl,"#")(1)end ifif instr(tmpurl,"index.asp")>0 thentmpurl=replace(tmpurl,"index.asp","index")end ifif instr(tmpurl,"default.asp")>0 thentmpurl=replace(tmpurl,"default.asp","default")end ifend ifasp2html_chgurl=asp2html_cpath(tmpurl)end ifend functionfunction asp2html_getsurl(str) '获取文件保存位置dim tmpurltmpurl=replace(replace(lcase(str),"http://",""),lcase(request.servervariables("s erver_name")),"")tmpurl=asp2html_chgurl(tmpurl)if right(tmpurl,5)<>".html" and right(tmpurl,4)<>".htm" thentmpurl=tmpurl&"index.htm"end ifasp2html_getsurl=tmpurlend functionfunction asp2html_savetxt(str,path) '保存文本文件dim ostreamset ostream=server.createobject("adodb.stream")ostream.type=2ostream.charset=asp2html_langostream.openostream.writetext strostream.savetofile server.mappath(path),2ostream.closeset ostream=nothingend functionsub asp2html(path) '主程序dim ohttp,ostream,obody,iurls,i,thisurlset ohttp=server.createobject("winhttp.winhttprequest.5.1")ohttp.settimeouts 5000,10000,15000,30000ohttp.open "GET",path,falseohttp.sendif ohttp.status<>200 thenresponse.write "访问:"&path&" 出现HTTP错误:"&ohttp.status&"|"&ohttp.statustext&"<br>"set ohttp=nothingexit subend ifobody=ohttp.responsebodyset ohttp=nothingobody=asp2html_b2s(obody)iurls=asp2html_gettag(obody)iurls=split(iurls,"|")thisurl=split(path,"/")(ubound(split(path,"/")))if thisurl="" thenthisurl="index.asp"elsethisurl=split(thisurl,"?")(0)end iffor i=0 to ubound(iurls)obody=asp2html_chgtag(obody,iurls(i),thisurl)nextasp2html_savetxt obody,asp2html_getsurl(path)end subasp2html("http://localhost/friend/kazi/en/index.asp") '注意路径不能写成相对路径,一定要是http地址,如果没有程序名最后一定要加"/"%>本来想做到循环所有链接的,但在编写的过程中出了些问题:我用一个变量保存每个页面的链接,以免陷入死循环,没想到,实现过程中却出了问题,本来的思路是:已经添加过的链接就不再添加了,并且不再访问了,但可能是递归的过程太快了的原因吧,老是循环添加一两个页面,取不到更多的页面出现像下面这样奇怪的问题:dim a,ba="123456"b="4"if instr(a,b)<0 thenresponse.write instr(a,b)end if结果仍然输出:4大家看看问题出在哪:<%server. script timeout=300'on error resume nextdim asp2html_urlsasp2html_urls="|"function asp2html_cpath(str) '过滤路径str=replace(str,"\","")str=replace(str,":","")str=replace(str,"*","")str=replace(str,"?","")str=replace(str,"<","")str=replace(str,">","")str=replace(str,"|","")str=replace(str,chr(34),"")str=replace(str,"//","/")asp2html_cpath=strend functionfunction asp2html_b2s(str,lang) '转换二进制数据为文本dim ostreamset ostream=server.createobject("adodb.stream")ostream.type=1ostream.mode=3ostream.openostream.write strostream.position=0ostream.type=2ostream.charset=langasp2html_b2s=ostream.readtextostream.closeset ostream=nothingend functionfunction asp2html_gettag(str) '获取所有链接dim r,matches,match,tmpurl,start,overstart="<a"over=">"set r=new regexpr.ignorecase=truer.global=truer.pattern=""&start&".+?"&over&""set matches=r.execute(lcase(str))set r=nothingstart=replace(start,"\","")over=replace(over,"\","")for each match in matchestmpurl=split(trim(replace(replace(lcase(match.value),"<a",""),">","")),"href=")( 1)if instr(tmpurl," ")>0 thentmpurl=split(tmpurl," ")(0)end ifif instr(tmpurl,chr(34))>0 thentmpurl=replace(tmpurl,chr(34),"",1,1)tmpurl=split(tmpurl,chr(34))(0)end ifif instr(tmpurl,chr(34)&"+")<1 and instr(tmpurl,"+"&chr(34))<1 and instr(tmpurl,"'+")<1 and instr(tmpurl,"+'")<1 and instr(tmpurl,"java script :")<1 thentmpurl=replace(replace(tmpurl,chr(34),""),"'","")if instr(asp2html_gettag,"|"&tmpurl)<1 and tmpurl<>"#" thenasp2html_gettag=asp2html_gettag&"|"&tmpurlend ifend ifnextif asp2html_gettag<>"" thenasp2html_gettag=replace(asp2html_gettag,"|","",1,1)end ifend functionfunction asp2html_chgtag(str,path,surl) '替换链接为静态链接dim r,iurl,turliurl=replace(path,"?","\?")iurl=replace(iurl,"+","\+")iurl=replace(iurl,"$","\$")turl=pathif left(turl,1)="?" thenturl=surl&turlend ifset r=new regexpr.ignorecase=truer.global=truer.pattern="(<a.*)(""| |'|=)"&iurl&"(""| |'|>)(.*>)"asp2html_chgtag=r.replace(str,"$1$2"&asp2html_chgurl(turl)&"$3$4")set r=nothingend functionfunction asp2html_chgurl(str) '转换动态链接为静态链接dim tmpurltmpurl=lcase(str)if left(tmpurl,7)="http://" and instr(tmpurl,lcase(request.servervariables("server_name")))<1 thenasp2html_chgurl=tmpurlelseif instr(tmpurl,".asp")>0 and right(tmpurl,4)<>".htm" thentmpurl=replace(tmpurl,"?","-")tmpurl=replace(tmpurl,"&","$")tmpurl=replace(tmpurl,"=","--")if instr(tmpurl,"#")<1 thentmpurl=tmpurl&".htm"elsetmpurl=split(tmpurl,"#")(0)&".htm#"&split(tmpurl,"#")(1)end ifif instr(tmpurl,"index.asp")>0 thentmpurl=replace(tmpurl,"index.asp","index")end ifif instr(tmpurl,"default.asp")>0 thentmpurl=replace(tmpurl,"default.asp","default")end ifend ifasp2html_chgurl=asp2html_cpath(tmpurl)end ifend functionfunction asp2html_getgurl(str,path) '获取绝对地址dim tmpurltmpurl=lcase(str)if left(tmpurl,7)<>"http://" thendim fpath,tpathfpath=lcase(path)if instr(fpath,"?")>0 thenfpath=split(fpath,"?")(0)end ifif instr(fpath,"#")>0 thenfpath=split(fpath,"#")(0)end iftpath=left(fpath,instrrev(fpath,"/"))if left(tmpurl,1)="?" thentmpurl=fpath&tmpurlelseif left(tmpurl,1)="#" thentmpurl=fpathelseif left(tmpurl,1)="/" thentmpurl="http://"&request.servervariables("server_name")&tmpurlelseif left(tmpurl,2)="./" thentmpurl=tpath&replace(tmpurl,"./","")elseif left(tmpurl,3)="../" thendo while left(tmpurl,3)="../"tpath=left(tpath,instrrev(replace(left(tpath,len(tpath)-1),"//",""),"/")+2) if instr(tpath,"http://")<1 thentpath="http://"&request.servervariables("server_name")&"/"end iftmpurl=replace(tmpurl,"../","",1,1)looptmpurl=tpath&tmpurlelsetmpurl=tpath&tmpurlend ifend ifasp2html_getgurl=tmpurlend functionfunction asp2html_getsurl(str) '获取文件保存位置dim tmpurltmpurl=replace(replace(lcase(str),"http://",""),lcase(request.servervariables("s erver_name")),"")tmpurl=asp2html_chgurl(tmpurl)if right(tmpurl,5)<>".html" and right(tmpurl,4)<>".htm" thentmpurl=tmpurl&"index.htm"end ifasp2html_getsurl=tmpurlend functionfunction asp2html_savetxt(str,lang,path) '保存文本文件dim ostreamset ostream=server.createobject("adodb.stream")ostream.type=2ostream.charset=langostream.openostream.writetext strostream.savetofile server.mappath(path),2ostream.closeset ostream=nothingend functionsub asp2html(path,lang,child) '主程序' path:程序路径' lang:生成的文件编码(如gb2312,utf-8)' child:0.整站模式(循环所有链接页面)' 1.仅针对当前页面' 2.针对当前页面及下一层页面' N.循环到当前面页面的第N-1层链接页面dim ohttp,ostream,obody,iurls,i,thisurlset ohttp=server.createobject("winhttp.winhttprequest.5.1")ohttp.settimeouts 5000,10000,15000,30000ohttp.open "GET",path,falseohttp.sendif ohttp.status<>200 thenresponse.write "访问:"&path&" 出现HTTP错误:"&ohttp.status&"|"&ohttp.statustext&"<br>"set ohttp=nothingexit subend ifobody=ohttp.responsebodyset ohttp=nothingobody=asp2html_b2s(obody,lang)iurls=asp2html_gettag(obody)iurls=split(iurls,"|")thisurl=split(path,"/")(ubound(split(path,"/")))if thisurl="" thenthisurl="index.asp"elsethisurl=split(thisurl,"?")(0)end iffor i=0 to ubound(iurls)obody=asp2html_chgtag(obody,iurls(i),thisurl)if instr(asp2html_urls,"|"&iurls(i)&"|")<1 thenif child<>1 and left(iurls(i),3)<>"../" and (left(lcase(iurls(i)),7)<>"http://" or instr(lcase(iurls(i)),lcase(request.servervariables("server_name")))>0) and left(iurls(i),1)<>"#" thenresponse.write iurls(i)&"|"&instr(asp2html_urls,"|"&iurls(i))&"<br>"if child=0 thenasp2html asp2html_getgurl(iurls(i),path),lang,0elseasp2html asp2html_getgurl(iurls(i),path),lang,child-1end if' response.write asp2html_getgurl(iurls(i),path)&"|"&child&"<br>"end ifasp2html_urls=asp2html_urls&iurls(i)&"|"end if' response.write iurls(i)&"|"&asp2html_chgurl(iurls(i))&"<br>"nextresponse.write"<Br>------------------------------------<br>"&asp2html_urls&"<br>----------------------------------<br>"asp2html_savetxt obody,lang,asp2html_getsurl(path)end subasp2html "http://localhost/friend/kazi/en/index.asp","gb2312",10%>如果你找到了出错的原因,请给我发一封邮件:sheo@谢谢!。
静态页⾯实例接前⼀⽂章:这个代码⽅案也是参考了很多⼈的代码写出的。
在此对这些⽆名的奉献者表⽰感谢。
贴⼀个核⼼的代码吧:}Cache.Add(url, string.Empty, null, DateTime.Now.AddSeconds(u.Cache), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.High, null); return;}}}if (writer is System.Web.UI.Html32TextWriter){writer = new FormFixerHtml32TextWriter(writer.InnerWriter);}else{writer = new FormFixerHtmlTextWriter(writer.InnerWriter);}base.Render(writer);}}public class FormFixerHtml32TextWriter : System.Web.UI.Html32TextWriter{public FormFixerHtml32TextWriter(TextWriter writer): base(writer){}public override void WriteAttribute(string name, string value, bool encode){// 如果当前输出的属性为form标记的action属性,则将其值替换为重写后的虚假URLif (pare(name, "action", true) == 0){value = HttpContext.Current.Request.RawUrl;}base.WriteAttribute(name, value, encode);}}public class FormFixerHtmlTextWriter : System.Web.UI.HtmlTextWriter{public FormFixerHtmlTextWriter(TextWriter writer): base(writer){}public override void WriteAttribute(string name, string value, bool encode){if (pare(name, "action", true) == 0)详细代码下载:有不清楚的地⽅,可以加QQ群:49745612⼀起探讨。
生成html静态页的多种方法用C#做脚本的的方法,这个是我自己写的,在《Visual C#.NET范例入门与提高》的P311,有对WebRequest和HttpRequest、HttpWebRequest、HttpWebResponse四个类的简单说明调用的时候这样:第二种方法是用一个html模板生成一个html页面,模版里面有对应的标签,可以从数据库和别的地方取数据,填写这个标签,生成一个html页面,这个方法在很多新闻系统里有用到我参考这里面的代码写的:出错:" + exp.Message);HttpContext.Current.Response.End();sr.Close();}// 替换内容// 对应模版里的设置要修改str = str.Replace("re_symbol_EventID", EventID);str = str.Replace("re_symbol_EventTitle", EventTitle);str = str.Replace("re_symbol_EventBody", EventBody);str = str.Replace("re_symbol_EventTime", EventTime);str = str.Replace("re_symbol_EventStat", EventStat);// 写文件try{sw = new StreamWriter(htmlfilepath + "\\" + htmlfilename, false, code);sw.Write(str);sw.Flush();}catch (Exception ex){HttpContext.Current.Response.Write("<p>写入文件出错:" + ex.Message);HttpContext.Current.Response.End();}finally{sw.Close();调用的时候这样://取内容,这里我取了页面上的一个gridview里的选中行的数据int i;i = GridView1.SelectedIndex;if (i == null || i==-1) i = 0;string EventID, EventTitle, EventBody, EventTime, EventStat;EventID=GridView1.Rows[i].Cells[0].T ext;EventTitle=GridView1.Rows[i].Cells[1].Text;EventBody=GridView1.Rows[i].Cells[2].Text;EventTime=GridView1.Rows[i].Cells[3].Text;EventStat=GridView1.Rows[i].Cells[4].Text;//生成文件,返回文件名string fna;fna=CreateDetailPage(EventID, EventTitle, EventBody, EventTime, EventStat);Response.Write("<p>生成文件成功:" + fna);。
通过ASP⽣成html纯静态页⾯的简单⽰例本站收录这篇⽂章通过ASP⽣成html纯静态页⾯的简单⽰例,详细解说⽂章中相关技术与知识,欢迎能给⼤家⼀些在这⽅⾯的⽀持和帮助!下⾯是详细内容:原理:通过浏览器传送变量,如代码:if SaveFile("/new/"&id&".html","http://127.0.0.1/news.asp?id="&id&"") then 中90这个变量相信⼤家会调⽤吧,这样就能在/new⽬录下⽣成按照id排列的html⽂章了shengcheng.asp⽂件如下:程序代码(For )如下:1. <%2.3. Dim id4.5. id = Request("id")6.7. %>8.9. <%10.11. if SaveFile("/new/"&id&".html","http://127.0.0.1/news.asp?id="&id&"") then12.13. Response.write "已⽣成"14.15. else16.17. Response.write "没有⽣成"18.19. end if20.21. function SaveFile(LocalFileName,RemoteFileUrl)22.23. Dim Ads, Retrieval, GetRemoteData24.25. On Error Resume Next26.27. Set Retrieval = Server.CreateObject("Microso" & "ft.XM" & "LHTTP") '//把单词拆开防⽌杀毒软件误杀28.29. With Retrieval30.31. .Open "Get", RemoteFileUrl, False, "", ""32.33. .Send34.35. GetRemoteData = .ResponseBody36.37. End With38.39. Set Retrieval = Nothing40.41. Set Ads = Server.CreateObject("Ado" & "db.Str" & "eam") '//把单词拆开防⽌杀毒软件误杀42.43. With Ads44.45. .Type = 146.47. .Open48.49. .Write GetRemoteData50.51. .SaveToFile Server.MapPath(LocalFileName), 252.53. .Cancel()54.55. .Close()56.57. End With58.59. Set Ads=nothing60.61. if err <> 0 then62.63. SaveFile = false64.65. err.clear66.67. else68.69. SaveFile = true70.71. end if72.73. End function74.75. %>。
ASP生成静态网页技术的实现
当今大型网站页面都改用了静态的页面,这是因为静态页面可以提高浏览速度,减轻服务器的负担,方便搜索引擎收录,网站更安全,静态页面从理论上讲是没有攻击漏洞的,基于以上的好处所以现在知名、主流的大站基本上都静下来了。
ASP(Active Server Pages)是 Web 的服务器端脚本编写环境,也是绝大多数从事网站开发人员很熟悉的编程环境。
如何用asp生成静态网页一般有两种方法:1使用FSO生成,2使用XMLHTTP生成。
下面将综合这两种方法来实现静态页的生成。
1 ASP生成静态页的方法
我们用标签替换的方法生成静态网页,做一个模版页
mb.asp,生成静态页的时候直接把需要变化的部分的标签替换掉就行了。
此例中我们把模板页mb.asp设置两个标签%title%和%content%。
模板页可以是静态页也可以是动态页,但出于实际应用的方便我们用动态页做为模板页。
静态网页执行页面为do.asp里面是具体生成静态页的代码。
2 程序中用到相关技术的方法和属性
1) Request.ServerVariables
Request.ServerVariables("Server_Name")服务器的主机名、DNS地址或IP地址
Request.ServerVariables("Server_Port")接受请求的
服务器端口号
Request.ServerVariables("Path_Info")客户端提供的路径信息
2) ADODB.Stream对象
mode 读写模式,可选值:1-读,2-写,3-读写
type 数据类型,可选值:1-二进制,2-文本
charset 编码方式,可选值:utf-8,gb2312
position 数据流位置,表示数据操作从这里开始,第一个位置的值为 0,不是 1。
size 数据流大小(字节)
LoadFromFile 从文件读取数据到 Stream 对象,Stream 对象原有内容将被清空
SaveToFile 将 Stream 对象数据保存为文件,第二个参数:1-不允许覆盖,2-覆盖写入
Open 打开数据流
Close 关闭数据流
Read([长度])从 Stream 对象中读取二进制数据,不指定长度表示全部读取
ReadText([长度])从 Stream 对象中读取文本数据,不指定长度表示全部读取
Write(buffer)将缓存数据写入 Stream 对象
WriteText(data, [option])将文本数据写入 Stream 对
象,第二个参数:0-字符写入,1-行写入
CopyTo(destStream, count)将 Stream 对象的指定数据拷贝到 destStream
3) MSXML2.XMLHTTP对象
Open( bstrMethod, bstrUrl, varAsync, bstrUser,bstrPassword )
bstrMethod:数据传送方式,即GET或POST。
bstrUrl:服务网页的URL。
varAsync:是否同步执行。
缺省为True,即同步执行,但只能在DOM中实施同步执行。
用中一般将其置为False,即异步执行。
bstrUser:用户名,可省略。
bstrPassword:用户口令,可省略。
Send( varBody )
varBody:指令集。
可以是XML格式数据,也可以是字符串,流,或者一个无符号整数数组。
也可以省略,让指令通过Open 方法的URL参数代入。
readyState 返回当前请求的状态,只读.
3 生成静态页的主要代码
80 Then URL = URL & ":" & SERVER_PORT
URL = URL & PATH_INFO
GetPageUrlPath = URL
End Function
function getHTTPPage(url)‘获取发送请求网页内容的函数dim Http
set Http=server.createobject("MSXML2.XMLHTTP")
Http.open "GET",url,false ‘设定向目标网页发送请求的方式
Http.send()
if Http.readystate4 then
exit function
end if
getHTTPPage=bytesToBSTR(Http.responseBody,"utf-8")‘对获取的内容转码
set http=nothing
if err.number0 then err.Clear
end function
Function BytesToBstr(body,Cset)‘转换编码函数
dim objstream
set objstream = Server.CreateObject("adodb.stream")objstream.Type = 1
objstream.Mode =3
objstream.Open
objstream.Write body
objstream.Position = 0
objstream.Type = 2
objstream.Charset = Cset
BytesToBstr = objstream.ReadText
objstream.Close
set objstream = nothing
End Function
function creatfile(filePath,nr)‘创建文件函数
Set objStream = Server.CreateObject("ADODB.Stream")objStream.Type = 2
objStream.Mode = 3
objStream.Open
objStream.Charset = "utf-8"
objStream.Position = objStream.Size
objStream.WriteText=nr
objStream.SaveToFile filePath,2
objStream.Close
Set objStream = Nothing
end function
'代码部分
SiteUrl = GetPageUrlPath()’ 获取服务器地址PageURL=SiteUrl & "mb.asp?time="&now()’得到模板
页网址
ReplaceContent = getHTTPPage(PageURL)’取得模板页内容
title="这是标题"
content="这是内容"
ReplaceContent= replace(ReplaceContent,"%title%",title)’替换标签
ReplaceContent = replace(ReplaceContent,"%content%",content)
pagename=server.mappath("a.html")’要生成静态页的名字
call creatfile(pagename,ReplaceContent)’调用函数创建静态网页
response.Write "生成文件成功"
4 结束语
程序执行的结果是在网站的根目录下生成了一个a.html的网页,通过这个例子我们可以将动态网站的首页、列表页和文章页都变成静态页从而使网站更安全高效地运行。