freemarker是一款java模板引擎,本质上是一个java类库,可以按照用户定义好的ftl模板文件来生成符合模板格式的动态页面,属于web应用的view表示层技术。
本文有两个小程序例子,展示了freemarker的两种不同用法:
1、使用ftl模板直接返回输出,类似于jsp
2、由ftl生成静态的html页面,这种技术适用于各种网站的后台内容管理系统。
首先看一下工程结构:
/** * Servlet implementation class HelloFreemarkerServlet */ @WebServlet("/HelloFreemarkerServlet") public class HelloFreemarkerServlet extends HttpServlet { private static final long serialVersionUID = 1L; private Configuration config = null; private final String TEMPLATE_URL = "/WEB-INF/templates"; /** * @see HttpServlet#HttpServlet() */ public HelloFreemarkerServlet() { super(); } @SuppressWarnings("deprecation") public void init(){ config = new Configuration(); config.setServletContextForTemplateLoading(getServletContext(), TEMPLATE_URL); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HashMap rootMap = new HashMap(); rootMap.put("message", "Hello world"); rootMap.put("name", "liny"); Template template = config.getTemplate("test.ftl"); response.setContentType("text/html; charset=" + template.getEncoding()); Writer out = response.getWriter(); try { template.process(rootMap, out); } catch (TemplateException e) { e.printStackTrace(); } } }
public class FreemarkerTest { public static void main(String[] args) throws IOException, TemplateException{ final String pagePath = "F:\workspace\freemarker\WebContent\"; final String templatePath = "F:\workspace\freemarker\WebContent\WEB-INF\templates"; HashMap map = new HashMap(); map.put("message", "你好"); map.put("name", "大臭"); Configuration config = new Configuration(); config.setDirectoryForTemplateLoading(new File(templatePath)); FileOutputStream fos = new FileOutputStream(pagePath+"test.html"); OutputStreamWriter writer = new OutputStreamWriter(fos); Template template = config.getTemplate("test.ftl"); template.process(map, writer); writer.flush(); writer.close(); } }
<html> <head> <title>freemarker测试</title> </head> <body> <h1>${message} , ${name}</h1> </body> </html>