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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值