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