使用Freemarker實現頁面靜態化

2021-09-02 16:30:53 字數 1638 閱讀 8241

在訪問新聞、活動、商品、詳情頁面的時候,路徑可以是xx【id】.html,伺服器端根據請求id,動態生成html網頁,下次訪問資料時,無需再查下資料,直接將html靜態頁面返回。可以減少對資料庫的互動,提高訪問的效能。

具體操作步驟

1.首先我們要有乙個freemarker模板物件

通常模板檔案放在web-inf下或者classes下,在web-inf的資料夾下建立template資料夾,然後建立hello.ftl檔案

2.在**中獲取到模板物件並將查出來的值放入模板中(鍵值對應每乙個值名字)

注意我們一般查資料庫的值查出來都是乙個物件,所以我們放的時候也放乙個物件,模板中取值就 物件名.屬性名 來取值即可

configuration configuration =newconfiguration(configuration.version_2_3_22);

configuration.setdirectoryfortemplateloading(new// 獲取模板物件

template template = configuration.gettemplate("hello.ftl");

//使用map集合建立動態資料物件

map parametermap =newhashmap();

parametermap.put("title", "程式設計師");

parametermap.put("msg", "你好,這是第乙個freemarker的案例");

3.將生成的頁面輸出(注意我們這裡是使用頁面的id來找對應的靜態化頁面的,但是我沒找到**有指定id生成頁面名,所以我暫時認為是按照id預設生成的,頁面上找對應的頁面也根據id來找即可)

template.process(parametermap,newoutputstreamwriter(newfileoutputstream(htmlfile),"utf-8"));

補充:如果已經生成的頁面我們通過位址直接找到頁面然後輸出即可

// 先判斷id,是否對應html,是否存在,如果存在,直接返回

// 查詢路徑中檔案

string htmlrealpath = servletactioncontext.getservletcontext().getrealpath("/freemarker");

file htmlfile =newfile(htmlrealpath + "/" + model.getid() + ".html");

servletactioncontext.getresponse().setcontenttype("text/html;charset=utf-8");

fileutils.copyfile(htmlfile, servletactioncontext.getresponse().getoutputstream());

JSP靜態頁例項 Freemarker例項

詳細 取得模板檔案 設定生成檔案路徑 載入objectmap中的內容生成檔案 詳細 取得模板檔案 設定生成檔案路徑 載入objectmap中的內容生成檔案 param templatefolder 模板相對於classpath的路徑 param templatefilename 模版名稱 param...

11 使用ForwardAction實現頁面遮蔽。

我們在jsp頁面之間寫鏈結總會是.jsp,而如果我們想遮蔽掉具體的jsp,只需要所jsp頁面配置成乙個forwardaction即可實現。示例如下 在根目錄下有乙個index.jsp主頁,我們strtus.xml中作如下配置 index.jsp 說明 如果沒有未action指定class,預設就是a...

Freemarker使用入門 servlet

freemarker是開源的模板框架。對於它的介紹網上已經很多了。詳情可參考主頁 4.在web inf目錄下建一資料夾templates,然後在這個資料夾裡面新建乙個模板檔案test.ftl 5.建乙個helloservlet protected void dopost httpservletreq...