一、下载freemarker的jar包,到maven仓库下载
二、引入jar包,参考freemarker的手册写代码
1、Test.ftlh
<!DOCTYPE html>
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<p>My name is ${username}, I'm ${age} years old, my birthday is ${date?string("yyyy-MM-dd")}</p>
</body>
</html>
2、com.freeMark.bean.User
package com.freeMark.bean; import java.util.Date; public class User { private String username; private int age; private Date date; public User(String username, int age, Date date) { this.username = username;
this.age = age;
this.date = date; } public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public Date getDate() {
return date;
} public void setDate(Date date) {
this.date = date;
} }
3、com.freeMark.FreemarkTest
package com.freeMark; import java.io.File;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Calendar;
import java.util.GregorianCalendar; import com.freeMark.bean.User; import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler; public class FreemarkTest { public static void main(String[] args) { Calendar calendar = new GregorianCalendar(, , ); User user = new User("youth", , calendar.getTime()); Configuration cfg = new Configuration(Configuration.VERSION_2_3_25); try {
//设置模板的地址
cfg.setDirectoryForTemplateLoading(new File("src/ftl")); cfg.setDefaultEncoding("UTF-8");
//设置报错处理方式
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); cfg.setLogTemplateExceptions(false);
//取得模板
Template temp = cfg.getTemplate("Test.ftlh"); Writer out = new OutputStreamWriter(System.out);
//设置模型数据
temp.process(user, out); } catch (Exception e) {
e.printStackTrace();
}
} }
三、输出结果
<!DOCTYPE html>
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<p>My name is youth, I'm 22 years old, my birthday is 1994-02-18</p>
</body>
</html>