靜态頁面化技術:根據id來查詢頁面,如果第一次通路沒有先生成html,當你再次通路這個html,不需要通路資料庫,直接傳回這個html,這樣就減少資料庫的互動,提高查詢速度;模闆+資料==輸出;
使用步驟
1.不需要導依賴:struts2有,如果不是用的,你可以自己導依賴
2.寫一個模闆的html。字尾名我一般用.ftl :防止亂碼有兩種方式
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
修改工具的字元集
3.在開發工具上加freemarker_eclipseplugin 複制導elipse的dropins下:這樣你就能用#{titel}
4.固定四步API
public String showDetail() throws Exception {
// 先判斷 id 對應html 是否存在,如果存在 直接傳回
String htmlRealPath = ServletActionContext.getServletContext()
.getRealPath("/freemarker");
File htmlFile = new File(htmlRealPath + "/" + model.getId() + ".html");
// 如果html檔案不存在 ,查詢資料庫,結合freemarker模闆生成 頁面
if (!htmlFile.exists()) {
Configuration configuration = new Configuration(
Configuration.VERSION_2_3_22);
configuration.setDirectoryForTemplateLoading(new File(
ServletActionContext.getServletContext().getRealPath(
"/WEB-INF/freemarker_templates")));
// 擷取模闆對象
Template template = configuration
.getTemplate("promotion_detail.ftl");
// 動态資料
Promotion promotion = WebClient
.create("http://localhost:9001/bos_management/services/promotionService/promotion/"
+ model.getId()).accept(MediaType.APPLICATION_JSON)
.get(Promotion.class);
Map<String, Object> parameterMap = new HashMap<String, Object>();
parameterMap.put("promotion", promotion);
// 合并輸出 這裡是要模闆有資料
template.process(parameterMap, new OutputStreamWriter(
new FileOutputStream(htmlFile), "utf-8"));
}
// 存在 ,直接将檔案傳回
ServletActionContext.getResponse().setContentType(
"text/html;charset=utf-8");
//傳回到頁面
FileUtils.copyFile(htmlFile, ServletActionContext.getResponse()
.getOutputStream());
return NONE;
}