初次接触free marker这个东西,鄙人也是小菜鸟一枚,琢磨了几天,算是勉强会用了,分享给大家,共勉。
1.首先就是环境配置,当然也可以直接导入jar包,一般情况下free marker-jar就够用了,有需要的话再加其他的包。
大家也可以在xml中进行配置,例;
2.然后就是他的使用了,很简单,数据模型+前端模板=静态网页,相信大家都在其他地方都能看到这些东西,举个我学习时使用的第一个例子:
(1)先看后端java代码(数据模型)
package com.b505.freemarker;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import org.bouncycastle.asn1.ocsp.Request;
import org.springframework.web.bind.annotation.RequestBody;
import freemarker.template.Configuration;
import freemarker.template.Template;
public class Test1 {
public static void main(String[] args) throws Exception {
//Test1 obj = new Test1();System.out.println("1");
//obj.init();System.out.println("1");
System.out.println("1");
Configuration cfg = new Configuration();System.out.println("10"); //建立模型
cfg.setDirectoryForTemplateLoading(new File("src\\main\\webapp\\freemarker\\Test"));System.out.println("100");
Map<String, Object> root = new HashMap<String, Object>(); System.out.println("1000");
root.put("user", "java2000.net");System.out.println("2");
Map<String, String> latestProduct = new HashMap<String, String>();System.out.println("3");
latestProduct.put("url", "http://www.java2000.net");System.out.println("4");
latestProduct.put("name", "Java世纪网");System.out.println("5");
root.put("latestProduct", latestProduct);System.out.println("6");
Template t = cfg.getTemplate("Test1.ftl");System.out.println("7");
Writer out = new OutputStreamWriter(new FileOutputStream("src\\main\\webapp\\Test1.jsp"), "utf-8");System.out.println("8");
t.process(root, out);
System.out.println("Successfull................");
}
}
(2)再看ftl格式的模板代码:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<h1>Welcome ${user}!</h1>
<p>Our latest product:
<a href="${latestProduct.url}">${latestProduct.name}</a>!
</body>
</html>
现在回过头来看,很简单了,大家共勉,有问题多交流。
欢迎关注公众号 IT技术自查 获取更多跟详细的IT情报