这几天在做国家教育平台阳光工程,由于考虑到将来的用户群比较多,所以我们考虑使用.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代码
$title$
$author$
$content$
二、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("
//固定
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
sbneartitle.AppendFormat("
}
sbneartitle.Remove(0, sbneartitle.ToString().Length);
sbneartitle.Append("
waitemp = waitemp.Replace("$HitsTitle$", sbneartitle.ToString());
sbneartitle.Remove(0, sbneartitle.ToString().Length);
}
if (waitemp.Contains("$Elite$"))
{
sbneartitle.Append("
sbneartitle.Append("
sbneartitle.Remove(0, sbneartitle.ToString().Length);
}
//相关Classid
if (waitemp.Contains("$ClassTitle$"))
{
sbneartitle.Append("
sbneartitle.Append("
//相关Classid
if (waitemp.Contains("$LikeTitle$"))
{
sbneartitle.Append("
/////////////////////////////////////////////////////////////////////////////////////////////
#endregion
//替换最新的数据
for (int j = 0; j
}
//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$", "" + temp1 + Convert.ToString(dt.Rows[0][dt.Columns[j].ColumnName.Trim()]) + temp2 + "");
waitemp = temp11 + temp22;
temp11 = null;
temp22 = null;
//waitemp = waitemp.Replace("$" + dt.Columns[j].ColumnName.Trim() + "$", "" +temp1+ Convert.ToString(dt.Rows[0][dt.Columns[j].ColumnName.Trim()]) +temp2+ "");
}
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;
}
///
/// 生成列表页
///
///
///
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; } //sbneilist.Append("
}
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(), "
//// MessageBox.Show(mat.Groups["content"].Value);
////
////
Match mat = Regex.Match(listcontent, "
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
//System.Text.StringBuilder sbneilist = new System.Text.StringBuilder(" System.Text.StringBuilder sbneilist = new System.Text.StringBuilder(head);
");
int l = 0;
for (int j = (i * size
//sbneilist.Append(" ");");
//string temp = listcontent;
string temp = body;
for (int k = 0; 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("");
}
else
{
sbneilist.Append(temp);
}
//sbneilist.Append(" ");
sbneilist.Append(page.Replace("¥pages¥", classes.Common.GetPage(i + 1, size, zong)));
// sbneilist.Append("
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
sbneartitle.AppendFormat("
}
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
sbneartitle.AppendFormat("
}
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
sbneartitle.AppendFormat("
}
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
sbneartitle.AppendFormat("
}
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
sbneartitle.AppendFormat("
}
sbneartitle.Append("");
templatewai = templatewai.Replace("$ClassTitle$", sbneartitle.ToString());
sbneartitle.Remove(0, sbneartitle.ToString().Length);
//sbneartitle.Append("
软件开发培训,项目实训,请到华海实训,一流经验,一流的项目实训师,软件工程师成长的摇篮。