关于.net生成静态页面的方法总结
这几天在做国家教育平台阳光工程,由于考虑到将来的用户群比较多,所以我们考虑使用.net生成静态页面的方法来减少数据与数据库的访问量,虽然以前也写过一些静态的页面,但是感觉没有将来的比较复杂,所以搜索了一下网络,再结合自己以前的一些经验,总结出以下几步思想:
1)做一个比较好的模板temp1.html,并在模板中写好题目,内容,作者 以及发布日期的标记,如果还有其他列表的话也要写好其他列表的标记,如 题目可以用标记:$Title$,内容可以用$cont$,发布日期$PubDate,最新发布新闻列表$DtNewest$;
2)设计数据库,可以设置两张表,一张表存放模板,一张用于存放发布新闻的内容
如 模板表: TempTable : ID ,classid,TempPath(存放模板的路径);
新闻表: NesTable: ID,ClassID,title,cont,Filepath(发布后存放静态页面的路径),pubdate,author,status;
3)添加新闻时,现在记录添加到新闻表中,然后再根据栏目的ID找到该栏目的模板,把模板中的内容读取到一个字符串变量中,并用新闻表中的字段替换模板中的相应标记,然后调用c#中的读写文件的类,写到一个静态文件中如:News.HTml,写成功后再更新数据中静态文件路径filepath;
这样一个静态文件就写好了
另外本人也从网络上搜集了一些资料,供大家参考(关于新闻内容分页的情况下次叙述)
一、类似的模板
模板页Text.html代码
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>$ShowArticle$</title>
<body>
$title$
<br>
$author$
<br>
$content$<br>
</body>
</HTML>
二、C#生成静态页类代码|支持列表生成代码
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using zj123.Model;
using System.IO;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
using System.Text;
using System.Collections;
namespace WebUI.html
{
public class EasyHtml
{
public bool MakeHtml(string artid)
{
bool succ = false;
int len = Convert.ToInt32(Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["titlelength"]) ?? "20");
//读取数据
string sql = string.Format("select a.*,b.ClassName,b.Depth,b.OrderBy,b.isTop,b.isList,b.IsLinks,b.Links,b.PicURL,b.ParentID,b.TemplateoutId,b.TemplateinNeiId,b.TemplateinListId from article a,zone b where a.classid=b.classid and a.Status=3 and a.articleid={0}", artid);
DataTable dt = DbHelperOleDb.Query(sql).Tables[0];
if(dt.Rows.Count>0)
{
//外模板
string waitemp = "";
DataTable waidt =DbHelperOleDb.Query(string.Format("select * from template where TemplateID={0}",Convert.ToString(dt.Rows[0]["TemplateoutId"]).Trim())).Tables[0];
if (waidt.Rows.Count > 0)
{
waitemp = Convert.ToString(waidt.Rows[0]["TemplateContent"]);
}
//内模板
string neitemp = "";
DataTable neidt = DbHelperOleDb.Query(string.Format("select * from template where TemplateID={0}", Convert.ToString(dt.Rows[0]["TemplateinNeiId"]).Trim())).Tables[0];
if (neidt.Rows.Count > 0)
{
neitemp = Convert.ToString(neidt.Rows[0]["TemplateContent"]);
}
//替换模板
waitemp = waitemp.Replace("$intemplate$", neitemp);
//替换类型
string tempclassname = classes.Common.GetP(Convert.ToString(dt.Rows[0]["classid"]));
waitemp = waitemp.Replace("$ClassName$", tempclassname);
#region "文章列表"
//最新的文章
System.Text.StringBuilder sbneartitle = new System.Text.StringBuilder("<div align=\"left\">");
DataTable nearTitledt = DbHelperOleDb.Query("select top 10 case when len(title)>" + len + " then substring(title,1," + len + ") else title end as Title,HtmlPath from article where iscreate=1 order by updatetime desc").Tables[0];
for (int i = 0; i < nearTitledt.Rows.Count; i++)
{
sbneartitle.AppendFormat("<li><a href=\"{0}\">{1}</a></li>",Convert.ToString(nearTitledt.Rows[i]["HtmlPath"]),Convert.ToString(nearTitledt.Rows[i]["Title"]));
}
sbneartitle.Append("</ol></div>");
waitemp = waitemp.Replace("$NearTitle$", sbneartitle.ToString());
sbneartitle.Remove(0,sbneartitle.ToString().Length);
if (waitemp.Contains("$OnTopTitle$"))
{
sbneartitle.Append("<div align=\"left\">");
//固定
nearTitledt = DbHelperOleDb.Query("select top 10 case when len(title)>" + len + " then substring(title,1," + len + ") else title end as Title,HtmlPath from article where iscreate=1 and OnTop=1 order by updatetime desc").Tables[0];
for (int i = 0; i < nearTitledt.Rows.Count; i++)
{
sbneartitle.AppendFormat("<li><a href=\"{0}\">{1}</a></li>", Convert.ToString(nearTitledt.Rows[i]["HtmlPath"]), Convert.ToString(nearTitledt.Rows[i]["Title"]));
}
sbneartitle.Remove(0, sbneartitle.ToString().Length);
sbneartitle.Append("</ol></div>");
waitemp = waitemp.Replace("$OnTopTitle$", sbneartitle.ToString());
sbneartitle.Remove(0, sbneartitle.ToString().Length);
}
if (waitemp.Contains("$HitsTitle$"))
{
sbneartitle.Append("<div align=\"left\">");
//热门
nearTitledt = DbHelperOleDb.Query("select top 10 case when len(title)>" + len + " then substring(title,1," + len + ") else title end as Title,HtmlPath from article where iscreate=1 and Hits>1000 order by Hits desc,updatetime desc").Tables[0];
for (int i = 0; i < nearTitledt.Rows.Count; i++)
{
sbneartitle.AppendFormat("<li><a href=\"{0}\">{1}</a></li>", Convert.ToString(nearTitledt.Rows[i]["HtmlPath"]), Convert.ToString(nearTitledt.Rows[i]["Title"]));
}
sbneartitle.Append("</ol></div>");
waitemp = waitemp.Replace("$HitsTitle$", sbneartitle.ToString());
sbneartitle.Remove(0, sbneartitle.ToString().Length);
}
if (waitemp.Contains("$Elite$"))
{
sbneartitle.Append("<div align=\"left\">");
//推荐Elite
nearTitledt = DbHelperOleDb.Query("select top 10 case when len(title)>" + len + " then substring(title,1," + len + ") else title end as Title,HtmlPath from article where iscreate=1 and Elite=1 order by updatetime desc").Tables[0];
for (int i = 0; i < nearTitledt.Rows.Count; i++)
{
sbneartitle.AppendFormat("<li><a href=\"{0}\">{1}</a></li>", Convert.ToString(nearTitledt.Rows[i]["HtmlPath"]), Convert.ToString(nearTitledt.Rows[i]["Title"]));
}
sbneartitle.Append("</ol></div>");
waitemp = waitemp.Replace("$Elite$", sbneartitle.ToString());
sbneartitle.Remove(0, sbneartitle.ToString().Length);
}
//相关Classid
if (waitemp.Contains("$ClassTitle$"))
{
sbneartitle.Append("<div align=\"left\">");
nearTitledt = DbHelperOleDb.Query("select top 10 case when len(title)>" + len + " then substring(title,1," + len + ") else title end as Title,HtmlPath from article where iscreate=1 and classid=" + Convert.ToString(dt.Rows[0]["classid"]) + " order by updatetime desc").Tables[0];
for (int curr = 0; curr < nearTitledt.Rows.Count; curr++)
{
sbneartitle.AppendFormat("<li><a href=\"{0}\">{1}</a></li>", Convert.ToString(nearTitledt.Rows[curr]["HtmlPath"]), Convert.ToString(nearTitledt.Rows[curr]["Title"]));
}
sbneartitle.Append("</ol></div>");
waitemp = waitemp.Replace("$ClassTitle$", sbneartitle.ToString());
sbneartitle.Remove(0, sbneartitle.ToString().Length);
}
//相关Classid
if (waitemp.Contains("$LikeTitle$"))
{
sbneartitle.Append("<div align='left'>");
DataTable dtlike = zj123.Model.Article.GetLike(artid);
for (int likei = 0; likei < dtlike.Rows.Count; likei++)
{
sbneartitle.AppendFormat("<li><a href=\"{0}\">{1}</a></li>", Convert.ToString(dtlike.Rows[likei]["HtmlPath"]), Convert.ToString(dtlike.Rows[likei]["Title"]));
}
sbneartitle.Append("</ol></div>");
waitemp = waitemp.Replace("$LikeTitle$", sbneartitle.ToString());
sbneartitle.Remove(0, sbneartitle.ToString().Length);
}
/////////////////////////////////////////////////////////////////////////////////////////////
#endregion
//替换最新的数据
for (int j = 0; j < dt.Columns.Count; j++)
{
if (dt.Columns[j].ColumnName.Trim() == "Title")
{
string temp1 = "";
string temp2 = "";
string typefont = Convert.ToString(dt.Rows[0]["TitleFontType"]);
if (typefont == "0")
{
temp1 = "<strong>";
temp2 = "</strong>";
}
else if (typefont == "1")
{
temp1 = "<em>";
temp2 = "</em>";
}
else if (typefont == "2")
{
temp1 = "<strong><em>";
temp2 = "</strong></em>";
}
else
{
}
//System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex();
//Match match = Regex.Matches();
//reg.Replace(waitemp, Convert.ToString(dt.Rows[0][dt.Columns[j].ColumnName.Trim()]), 1, waitemp.IndexOf("$Title$"));
string temp11 = waitemp.Substring(0, waitemp.IndexOf("$Title$") + 8);
string temp22 = waitemp.Substring(waitemp.IndexOf("$Title$") + 8);
temp11 = temp11.Replace("$Title$", Convert.ToString(dt.Rows[0][dt.Columns[j].ColumnName.Trim()])+"---"+Regex.Replace(Regex.Replace(tempclassname,"<[^>]*>",""),"[>|<]*",""));
temp22 = temp22.Replace("$Title$", "<font color='" + Convert.ToString(dt.Rows[0]["TitleFontColor"]) + "'>" + temp1 + Convert.ToString(dt.Rows[0][dt.Columns[j].ColumnName.Trim()]) + temp2 + "</font>");
waitemp = temp11 + temp22;
temp11 = null;
temp22 = null;
//waitemp = waitemp.Replace("$" + dt.Columns[j].ColumnName.Trim() + "$", "<font color='" + Convert.ToString(dt.Rows[0]["TitleFontColor"]) + "'>" +temp1+ Convert.ToString(dt.Rows[0][dt.Columns[j].ColumnName.Trim()]) +temp2+ "</font>");
}
else if (dt.Columns[j].ColumnName.Trim().ToLower() == "hits")
{
waitemp = waitemp.Replace("$" + dt.Columns[j].ColumnName.Trim() + "$", Convert.ToInt16(dt.Rows[0][dt.Columns[j].ColumnName.Trim()]) > 1000 ? ("热门") : (""));
}
else if (dt.Columns[j].ColumnName.Trim().ToLower() == "ontop")
{
waitemp = waitemp.Replace("$" + dt.Columns[j].ColumnName.Trim() + "$", Convert.ToString(dt.Rows[0][dt.Columns[j].ColumnName.Trim()]).ToLower() == "true" ? ("置顶") : (""));
}
else if (dt.Columns[j].ColumnName.Trim().ToLower() == "elite")
{
waitemp = waitemp.Replace("$" + dt.Columns[j].ColumnName.Trim() + "$", Convert.ToString(dt.Rows[0][dt.Columns[j].ColumnName.Trim()]).ToLower().ToString() == "true" ? ("推荐") : (""));
}
else
{
waitemp = waitemp.Replace("$" + dt.Columns[j].ColumnName.Trim() + "$", Convert.ToString(dt.Rows[0][dt.Columns[j].ColumnName.Trim()]));
}
}
//替换链表信息
//$typejs$
waitemp = waitemp.Replace("$typejs$", Convert.ToString(dt.Rows[0]["ClassID"]));
//$numjs$
waitemp = waitemp.Replace("$numjs$", "10");
//$setjs$
waitemp = waitemp.Replace("$setjs$","");
///js脚本信息
//根据路径生成页面
//路径 检查
string path = System.Web.HttpContext.Current.Request.PhysicalApplicationPath.Trim() + Convert.ToString(dt.Rows[0]["Links"]) + "\\" + Convert.ToDateTime(dt.Rows[0]["CreateTime"]).ToString("yyyy-MM");
if(!Directory.Exists(path))
Directory.CreateDirectory(path);
string filename = "\\"+ Convert.ToString(dt.Rows[0]["ArticleID"]) + ".html";
using(StreamWriter sw = new StreamWriter(path+"\\"+filename,false,System.Text.Encoding.GetEncoding("gb2312")))
{
sw.Write(waitemp);
sw.Flush();
sw.Close();
}
//修改文章转台
try
{
if (artid == null)
return false;
int j = int.Parse(artid);
}
catch
{
return false;
}
string sql1 = string.Format("update article set iscreate=1,htmlpath='{0}' where articleid={1}", "/" + Convert.ToString(dt.Rows[0]["Links"]).Replace("\\\\", "/") + "/" + Convert.ToDateTime(dt.Rows[0]["CreateTime"]).ToString("yyyy-MM") + filename, artid);
DbHelperOleDb.ExecuteSql(sql1);
}
else
{
return false;
}
return succ;
}
/// <summary>
/// 生成列表页
/// </summary>
/// <param name="classid"></param>
/// <returns></returns>
public bool MakeList(string classid)
{
int len = Convert.ToInt32(Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["titlelength"]) ?? "20");
bool succ = false;
try
{
int i = int.Parse(classid);
}
catch
{
return false;
}
DataTable dt = DbHelperOleDb.Query(string.Format("select a.*,b.ClassName,b.Depth,b.OrderBy,b.isTop,b.isList,b.IsLinks,b.Links,b.PicURL,b.ParentID,b.TemplateoutlistId,b.TemplateoutId,b.TemplateinNeiId,b.TemplateinListId,b.keywords,b.[description] from article a,zone b where a.classid=b.classid and iscreate=1 and a.Status=3 and a.classid={0} order by a.UpdateTime desc,OnTop desc,Elite desc,Hits desc", classid)).Tables[0];
if (dt.Rows.Count > 0)
{
string classpath = HttpContext.Current.Request.PhysicalApplicationPath + @"\" + Convert.ToString(dt.Rows[0]["Links"]).Trim();
//读取外模板信息
string templatewai = "";
DataTable templatewaidt = DbHelperOleDb.Query(string.Format("select * from template where TemplateID={0}", Convert.ToString(dt.Rows[0]["TemplateoutlistId"]))).Tables[0];
if (templatewaidt.Rows.Count > 0)
{
templatewai = Convert.ToString(templatewaidt.Rows[0]["TemplateContent"]);
}
//根据类型替换标题
string tempclassname = classes.Common.GetP(classid);
templatewai = templatewai.Replace("$Title$", Convert.ToString(dt.Rows[0]["ClassName"]).Trim() +"--"+Regex.Replace(Regex.Replace(tempclassname,"<[^>]*>",""),"[<|>]*",""));
templatewai = templatewai.Replace("$ClassTitleTop$", Convert.ToString(dt.Rows[0]["ClassName"]).Trim());
templatewai = templatewai.Replace("$ClassName$", tempclassname);
templatewai = templatewai.Replace("$Keyword$", Convert.ToString(dt.Rows[0]["Keywords"]).Trim());
templatewai = templatewai.Replace("$Description$", Convert.ToString(dt.Rows[0]["Description"]).Trim());
int zong = dt.Rows.Count;
int size = 10;
try
{
size = Convert.ToInt16(System.Configuration.ConfigurationManager.AppSettings["pagesize"]);
}
catch
{
size = 10;
}
int pagecount = zong % size == 0 ? (zong / 10) : (zong / 10 + 1);
string listcontent = "";
DataTable dtlist = DbHelperOleDb.Query(string.Format("select * from template where TemplateID={0}", Convert.ToString(dt.Rows[0]["TemplateinListId"]))).Tables[0];
if (dtlist.Rows.Count > 0)
{
listcontent = Convert.ToString(dtlist.Rows[0]["TemplateContent"]);
}
//// Match mat = Regex.Match(this.rtbconten.Text.Trim(), "<tablehead>(?<content>.*)<tableheadend><tablebody></tablebodyend><tablepage></tablepage><tablebottom></tablebottomend>", RegexOptions.Multiline | RegexOptions.IgnoreCase);
//// MessageBox.Show(mat.Groups["content"].Value);
////<tablehead>(?<content>.*)<tableheadend><tablebody></tablebodyend><tablepage></tablepage><tablebottom></tablebottomend>
////
Match mat = Regex.Match(listcontent, "<tablehead>(?<head>.*)<tableheadend><tablebody>(?<body>.*)</tablebodyend><tablepage>(?<page>.*)</tablepage><tablebottom>(?<bottom>.*)</tablebottomend>",RegexOptions.IgnoreCase|RegexOptions.Multiline);
string head = Convert.ToString(mat.Groups["head"]);
string body = Convert.ToString(mat.Groups["body"]);
string page = Convert.ToString(mat.Groups["page"]);
string bottom = Convert.ToString(mat.Groups["bottom"]);
//循环生成分页
for (int i = 0; i < pagecount; i++)
{
//System.Text.StringBuilder sbneilist = new System.Text.StringBuilder("<TABLE cellSpacing=0 cellPadding=0 width=760 border=0><TBODY>");
System.Text.StringBuilder sbneilist = new System.Text.StringBuilder(head);
int l = 0;
for (int j = (i * size < zong) ? (i * size) : (zong); j < ((i + 1) * size < zong ? ((i + 1) * size) : (zong)); j++)
{
//sbneilist.Append(" <TR><TD vAlign=top align=center bgColor=#f7f7f7 >");
//string temp = listcontent;
string temp = body;
for (int k = 0; k < dt.Columns.Count; k++)
{
temp = temp.Replace("$" + dt.Columns[k].ColumnName.Trim() + "$", Convert.ToString(dt.Rows[j][dt.Columns[k].ColumnName.Trim()]));
}
if ((++l) % 5 == 0)
{
sbneilist.Append(temp).Append("<dd class=\"l\"></dd>");
}
else
{
sbneilist.Append(temp);
}
//sbneilist.Append("</td></tr>");
}
//sbneilist.Append("<TR><TD height=36>").Append(classes.Common.GetPage(i + 1, size, zong)).Append("</td></tr>");
sbneilist.Append(page.Replace("¥pages¥", classes.Common.GetPage(i + 1, size, zong)));
// sbneilist.Append("</tbody></table>");
sbneilist.Append(bottom);
#region "文章列表"
//最新的文章
System.Text.StringBuilder sbneartitle = new System.Text.StringBuilder("");
DataTable nearTitledt = DbHelperOleDb.Query("select top 10 case when len(title)>" + len + " then substring(title,1," + len + ") else title end as Title,HtmlPath from article where iscreate=1 order by updatetime desc").Tables[0];
for (int curr = 0; curr < nearTitledt.Rows.Count; curr++)
{
sbneartitle.AppendFormat("<li>·<a href=\"{0}\">{1}</a></li>", Convert.ToString(nearTitledt.Rows[curr]["HtmlPath"]), Convert.ToString(nearTitledt.Rows[curr]["Title"]));
}
sbneartitle.Append("");
templatewai = templatewai.Replace("$NearTitle$", sbneartitle.ToString());
sbneartitle.Remove(0, sbneartitle.ToString().Length);
sbneartitle.Append("");
//固定
nearTitledt = DbHelperOleDb.Query("select top 10 case when len(title)>" + len + " then substring(title,1," + len + ") else title end as Title,HtmlPath from article where iscreate=1 and OnTop=1 order by updatetime desc").Tables[0];
for (int curr = 0; curr < nearTitledt.Rows.Count; curr++)
{
sbneartitle.AppendFormat("<li>·<a href=\"{0}\">{1}</a></li>", Convert.ToString(nearTitledt.Rows[curr]["HtmlPath"]), Convert.ToString(nearTitledt.Rows[curr]["Title"]));
}
sbneartitle.Remove(0, sbneartitle.ToString().Length);
sbneartitle.Append("");
templatewai = templatewai.Replace("$OnTopTitle$", sbneartitle.ToString());
sbneartitle.Remove(0, sbneartitle.ToString().Length);
sbneartitle.Append("");
//热门
nearTitledt = DbHelperOleDb.Query("select top 10 case when len(title)>" + len + " then substring(title,1," + len + ") else title end as Title,HtmlPath from article where iscreate=1 and Hits>1000 order by Hits desc,updatetime desc").Tables[0];
for (int curr = 0; curr < nearTitledt.Rows.Count; curr++)
{
sbneartitle.AppendFormat("<li>·<a href=\"{0}\">{1}</a></li>", Convert.ToString(nearTitledt.Rows[curr]["HtmlPath"]), Convert.ToString(nearTitledt.Rows[curr]["Title"]));
}
sbneartitle.Append("");
templatewai = templatewai.Replace("$HitsTitle$", sbneartitle.ToString());
sbneartitle.Remove(0, sbneartitle.ToString().Length);
sbneartitle.Append("");
//推荐Elite
nearTitledt = DbHelperOleDb.Query("select top 10 case when len(title)>" + len + " then substring(title,1," + len + ") else title end as Title,HtmlPath from article where iscreate=1 and Elite=1 order by updatetime desc").Tables[0];
for (int curr = 0; curr < nearTitledt.Rows.Count; curr++)
{
sbneartitle.AppendFormat("<li>·<a href=\"{0}\">{1}</a></li>", Convert.ToString(nearTitledt.Rows[curr]["HtmlPath"]), Convert.ToString(nearTitledt.Rows[curr]["Title"]));
}
sbneartitle.Remove(0, sbneartitle.ToString().Length);
sbneartitle.Append("");
templatewai = templatewai.Replace("$Elite$", sbneartitle.ToString());
sbneartitle.Append("");
//相关Classid
nearTitledt = DbHelperOleDb.Query("select top 10 case when len(title)>" + len + " then substring(title,1," + len + ") else title end as Title,HtmlPath from article where iscreate=1 and classid=" + classid + " order by updatetime desc").Tables[0];
for (int curr = 0; curr < nearTitledt.Rows.Count; curr++)
{
sbneartitle.AppendFormat("<li>·<a href=\"{0}\">{1}</a></li>", Convert.ToString(nearTitledt.Rows[curr]["HtmlPath"]), Convert.ToString(nearTitledt.Rows[curr]["Title"]));
}
sbneartitle.Append("");
templatewai = templatewai.Replace("$ClassTitle$", sbneartitle.ToString());
sbneartitle.Remove(0, sbneartitle.ToString().Length);
//sbneartitle.Append("<div align='left'>");
//DataTable dtlike = zj123.Model.Article.GetLike(artid);
//for (int likei = 0; likei < dtlike.Rows.Count; likei++)
//{
// sbneartitle.AppendFormat("<li><a href=\"{0}\">{1}</a></li>", Convert.ToString(dtlike.Rows[likei]["HtmlPath"]), Convert.ToString(dtlike.Rows[likei]["Title"]));
//}
//sbneartitle.Append("</ol></div>");
//waitemp = waitemp.Replace("$LikeTitle$", sbneartitle.ToString());
//sbneartitle.Remove(0, sbneartitle.ToString().Length);
/////////////////////////////////////////////////////////////////////////////////////////////
#endregion
//替换链表信息
//$typejs$
templatewai = templatewai.Replace("$typejs$", classid);
//$numjs$
templatewai = templatewai.Replace("$numjs$", "10");
//$setjs$
templatewai = templatewai.Replace("$setjs$", "");
string tempzong = templatewai.Replace("$intemplate$", sbneilist.ToString());
string indexshow = (i + 1).ToString() == "1" ? ("") : ((i + 1).ToString());
-
资料引用:http://www.knowsky.com/534686.html