1,maven坐标html
<dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.23</version> </dependency>
2,模板文件,index.ftljava
<html> <head> <meta charset="utf-8"> <title>Freemarker入门小DEMO </title> </head> <body> <#--我只是一个注释,我不会有任何输出 --> ${name},你好。${message}<br/> <#if success??> 你已经过实名认证 <#else> 你未经过实名认证 </#if> </html>
3,java代码maven
pojocode
public class Person { private String name; private String message; private String success;
import com.freemark.pojo.Person; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; import java.io.*; public class FreemarkMain { public static void main(String[] args) throws IOException, TemplateException { //1.建立配置类 Configuration configuration=new Configuration(Configuration.getVersion()); //2.设置模板所在的目录 configuration.setDirectoryForTemplateLoading(new File("src/main/resources/templates/")); //3.设置字符集 configuration.setDefaultEncoding("utf-8"); //4.加载模板 Template template = configuration.getTemplate("index.ftl"); //5.建立数据模型 Person person = new Person(); person.setName("小苏"); person.setSuccess(""); person.setMessage(null); //6.建立Writer对象 // Writer out =new FileWriter(new File("d:\\test.html")); Writer out = new OutputStreamWriter(System.out); //7.输出 template.process(person, out); } }
4,项目结构xml