Freemarker生成HTML静态页面

  • 格式:pdf
  • 大小:74.62 KB
  • 文档页数:2

Freemarker⽣成HTML静态页⾯

这段时间的⼯作是做⼀个⽹址导航的项⽬,⾯向⽤户的就是⼀个⾸页,于是就想到了使⽤freemarker这个模板引擎来对⾸页静态化。

之前是⽤jsp实现,为了避免⽤户每次打开页⾯都查询⼀次数据库,所以使⽤了jsp的内置对象application,在Controller中将数据都查询

出来,

然后放⼊application,最后在JSP页⾯使⽤jstl标签配合EL表达式 将数据遍历出来。这样做是从⼀定程度上减轻了服务器的压⼒和页⾯的响

应速度,

但是仍然没有静态页⾯响应快。

使⽤Freemarker步骤:

1. jar包,我的项⽬中使⽤maven来构建,所以在pom.xml中引⼊Freemarker jar包的坐标就可以了。

2. ftl模板,我在WEB-INF下⾯创建⼀个⽂件夹ftl,⾥⾯只放ftl模板⽂件,我创建了⼀个index.ftl⽂件。

3. ftl模板⽂件中写的就是html标签和css样式之类的,但是数据部分需要使⽤Freemarker提供的标签遍历出来。如下

其中<#list>是Freemarker提供的遍历标签,Freemarker提供了很多的标签,这⾥不⼀⼀叙述。

4. Contorller中将数据都查询出来,通过ftl模板取出数据,最后将完整的数据写⼊html

// 获取搜索引擎

List searchEngines = this.indexService.findSearchEngines();

// 获取热搜客户

List hotSearchs = this.indexService.findHotSearchs();

// 获取前25个⼀级⽬录

CatalogCustom custom = new CatalogCustom();

custom.setCatalogLevel(1);

List topLevelCatalog = this.indexService.findCustomers(custom);

// 获取⼀级⽬录下的前⼗个客户

Map> customerMap = new HashMap>();

for (Catalog catalog : topLevelCatalog) {

CatalogCustom customer = new CatalogCustom();

customer.setCatalogLevel(3);

customer.setGfid(catalog.getCatalogId());

List customerList = this.indexService.findCustomers(customer);

customerMap.put(catalog.getCatalogName(), customerList);

}

// 获取新闻相关数据

Map> newsMap = new HashMap>();

List newsCatalogs = this.indexService.findNewsCatalog();

for (NewsCatalog newsCatalog : newsCatalogs) {

News news = new News(); news.setPid(newsCatalog.getId());

List newsList = this.indexService.findNews(news);

newsMap.put(newsCatalog.getNewscatalog(), newsList);

}

// 获取关键词

List keywords = this.indexService.findKeywords();

/*

application.setAttribute("newsMap", newsMap);

application.setAttribute("searchEngines", searchEngines);

application.setAttribute("hotSearchs", hotSearchs);

application.setAttribute("customerMap", customerMap);

application.setAttribute("keywords", keywords);

*/

String ftlPath = session.getServletContext().getRealPath("/WEB-INF/ftl");

Configuration configuration = new Configuration();

configuration.setDirectoryForTemplateLoading(new File(ftlPath));

configuration.setDefaultEncoding("UTF-8");

// 获取或创建⼀个模版。

Template template = configuration.getTemplate("index.ftl");

// 获取html静态页⾯⽂件

String indexPath = session.getServletContext().getRealPath("/index.html");

//设置⽂件输⼊流编码,不然⽣成的html⽂件会中⽂乱码

FileWriterWithEncoding out = new FileWriterWithEncoding(indexPath,"UTF-8");

// 将页⾯中要展⽰的数据放⼊⼀个map中

HashMap map = new HashMap();

map.put("newsMap", newsMap);

map.put("searchEngines", searchEngines);

map.put("hotSearchs", hotSearchs);

map.put("customerMap", customerMap);

map.put("keywords", keywords);

//将map中的数据输⼊到index.ftl这个模板⽂件中并遍历出来,最后再将整个模板的数据写⼊到index.html中。

template.process(map, out);

out.close();