天天看点

Freemarker的用法

静态页面化技术:根据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;

}