静态页面:.html .htm
原因:1.访问速度快 2.减轻数据库访问压力 是网站优化中很重要的手段
缺点:1.数据是写死的,不是所有页面都适合做成静态页面
什么样的内容适合做成静态页面?
经常访问的页面,但是页面的内容不是经常修改的
例如:新闻的详细页面、文章、小说、商品的详细页面
为什么不用页面缓存?
页面太多,占内存太大,静态页面是放在磁盘上的,做成页面缓存,需要在.net Framework管道里进行判断,没有必要做成页面缓存
一般步骤:管理员登录后台,在添加图书信息到数据库后,再生成静态页面(可以放一个复选框:是否生成静态页面)
BLL层代码:
///----------------------------
///生成静态页面
public void CreateHtmlPage(int id)
{
Model.Books model = dal.GetModel(id);
//获取文件
string template = HttpContext.Current.Request.MapPath("/Template/BookTemplate.html");
string fileContent = File.ReadAllText(template);
fileContent = fileContent.Replace("$title", model.Title).Replace("$author", model.Author).Replace("$unitprice", model.UnitPrice.ToString("0.00")).Replace("$isbn", model.ISBN).Replace("$Content", model.ContentDescription).Replace("$bookId", model.Id.ToString());
string dir = "/HtmlPage/" + model.PublishDate.Year + "/" + model.PublishDate.Month + "/" + model.PublishDate.Day + "/";
Directory.CreateDirectory(Path.GetDirectoryName(HttpContext.Current.Request.MapPath(dir)));
string fullDir = dir + model.Id + ".html";
File.WriteAllText(HttpContext.Current.Request.MapPath(fullDir), fileContent, System.Text.Encoding.UTF8);
}
CreatStaticPage.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CreatStaticPage.aspx.cs" Inherits="BookShop.Web.AdminManager.CreatStaticPage" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="submit" value ="生成静态页面" />
</div>
</form>
</body>
</html>
CreatStaticPage.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace BookShop.Web.AdminManager
{
public partial class CreatStaticPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{
//测试代码:前十条
BLL.BooksManager bll = new BLL.BooksManager();
List<Model.Books> list = bll.GetModelList("");
foreach(Model.Books bookModel in list)
{
bll.CreateHtmlPage(bookModel.Id);
}
}
}
}
}