略
freemarker 是Struts-core包中的一个依赖包,它可以实现动态页面的静态化,当某页面不经常发生改变时,使用静态化的页面可以减少对底层数据库的使用,从而减少数据库的压力.
使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| String htmlRealPath = ServletActionContext.getServletContext().getRealPath("/freemarker");
File htmlFile = new File(htmlRealPath + "/" + model.getId() + ".html");
System.out.println(htmlRealPath);
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(Constants.BOS_MANAGEMENT_URL + "/services/promotionService/promotion/" + model.getId()) .accept(MediaType.APPLICATION_JSON).get(Promotion.class); Map<String, Object> map = new HashMap<>(); map.put("promotion", promotion);
template.process(map, new OutputStreamWriter(new FileOutputStream(htmlFile), "utf-8"));
}
ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
FileUtils.copyFile(htmlFile, ServletActionContext.getResponse().getOutputStream());
|
模板promotion_detail.ftl
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| <link rel="stylesheet" type="text/css" href="css/promotion_detail.css"> <div class="container promotions" > <div class="col-md-2 prolist"> <h5 class="title"><a href="#/promotion"><strong>返回促销列表</strong></a></h5> <img src="images/pro.jpg" class="img-responsive"> </div> <div class="col-md-10 procontent"> <h5 class="title">${promotion.title}</h5> <div class="intro"> <p>活动范围: ${promotion.activeScope}</p> <p>活动时间: ${promotion.startDate?string("yyyy-MM-dd")} - ${promotion.endDate?string("yyyy-MM-dd")}</p> </div> <div class="partline clearfix"></div> <div class="promotionbox"> ${promotion.description} </div> </div> </div>
|
通过EL表达式接收数据并显示出来,还可以使用函数来解析传来的数据,例如:
1 2
| ${promotion.startDate?string("yyyy-MM-dd")} ${promotion.endDate?string("yyyy-MM-dd")}
|