freemarker

it2022-05-05  161

 

 1、freemarker基本使用

@Test public void freemarker() throws IOException, TemplateException { //1、创建一个模板文件 //2、创建一个Configuration对象 Configuration configuration = new Configuration(Configuration.getVersion()); //3、设置模板文件的保存位置 configuration.setDirectoryForTemplateLoading(new File("F:\\workspace\\idea\\e3\\e3-item-web\\src\\main\\webapp\\WEB-INF\\ftl")); //4、模板文件的编码格式 configuration.setDefaultEncoding("UTF-8"); //5、加载模板文件,创建一个模板对象 Template template = configuration.getTemplate("hello.ftl"); //6、创建一个数据集 Map<String, Object> data = new HashMap<>(); data.put("hello", "success"); Student student = new Student(1, "小明", 18, "回龙观"); data.put("student", student); //7、创建一个Writer对象 Writer writer = new FileWriter("F:\\workspace\\freemarker\\hello.txt"); //8、生成静态页面 template.process(data, writer); }

 

 2、访问pojo属性

Map<String, Object> data = new HashMap<>(); Student student = new Student(1, "小明", 18, "回龙观"); data.put("student", student);    学生信息:<br> 学号:${student.id}   &nbsp; 姓名:${student.name}   &nbsp; 年龄:${student.age}   &nbsp; 家庭住址:${student.address}<br>

 

3、list集合

List<Student> stuList = new ArrayList<>(); stuList.add(new Student(1, "小明1", 18, "成都")); stuList.add(new Student(2, "小明2", 19, "达州")); data.put("stuList", stuList);

 

<table border="1"> <tr> <th>序号</th> <th>学号</th> <th>姓名</th> <th>年龄</th> <th>家庭住址</th> </tr> <#list stuList as stu> <#if stu_index % 2 == 0> <tr bgcolor="red"> <#else> <tr bgcolor="green"> </#if> <td>${stu_index}</td> <td>${stu.id}</td> <td>${stu.name}</td> <td>${stu.age}</td> <td>${stu.address}</td> </tr> </#list> </table>

 

3、data类型的处理

可以使用?date,?time,?datetime,?string(parten)–&gt; 当前日期:${date?string("yyyy/MM/dd HH:mm:ss")}<br> null值的处理:${val!"val的值为null"}<br> 判断val的值是否为null:<br> <#if val??> val中有内容 <#else> val的值为null </#if>

 

4、引入模板

引用模板测试:<br> <#include "hello.ftl">

 

 

 

 

 

           

转载于:https://www.cnblogs.com/lzb0803/p/9126981.html

相关资源:安装freemarker插件(freemarker的eclipse插件)

最新回复(0)