-
什么是freemaker
FreeMaker是一款模版引擎:基于模版和要改变的数据,并用来生成输出文本(HTML、配置文件)的工具,主要用Freemarker做静态页面或是页面展示
简而言之:Freemaker是一个模版引擎,一个基于模版文件生成输出的工具,使用java编写 -
FreeMaker在servlet中的使用
1)导入依赖
<dependency>
<groupId>freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.8</version>
</dependency>
2)编写servlet
private UserService userService = new UserService();
//freemaker 实例
private Configuration configuration;
//数据驱动
Map<String,Object> root;
@Override
public void init(ServletConfig config) throws ServletException {
//实例化freemaker
configuration = new Configuration();
//设置模版文件存放目录
//方法一 :使用servletContext
configuration.setServletContextForTemplateLoading(this.getServletContext(),"WEB-INF/templates");
//方法二:使用类路径
//configuration.setClassForTemplateLoading(this.getClass(),"/templates");
//方法三:使用系统文件
/*try {
configuration.setDirectoryForTemplateLoading(new File("/templates"));
} catch (IOException e) {
e.printStackTrace();
}*/
//设置模版缓存时间
configuration.setTemplateUpdateDelay(5000);
//设置缓存策略
configuration.setCacheStorage(new MruCacheStorage(20,250));
String path = this.getServletContext().getContextPath();
root.put("path",path);
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getParameter("method");
if("query".equals(method)){
try {
this.query(req,resp);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}
}
}
private void query(HttpServletRequest req, HttpServletResponse resp) throws SQLException, ClassNotFoundException, IOException, TemplateException {
List<?> list = userService.queryManagerList();
root.put("list",list);
Template template = configuration.getTemplate("/user/user_list.ftl");
template.process(root,resp.getWriter());
}
3)编写ftl文件
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>User模块的查询展示页面</title></head>
<a href="${path}manage/user.do?method=addpage">进入添加页面</a>
<table border="1">
<tr>
<td>用户id</td>
<td>用户名</td>
<td>密码</td>
<td>标识†</td>
<td>操作</td>
</tr>
<#list list as user >
<tr>
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.pwd}</td>
<td>${user.note}</td>
<td>
<a href="${path}manage/user.do?method=editpage&id=${user.id}">修改</a>
<a href="${path}manage/user.do?method=delete&id=${user.id}">删除</a>
</td>
</tr>
</#list>
</table>
</body>
</html>
- Struts对freemaker的支持