初见Freemarker
题记:初步写了下感觉和JSP差不多,不过好像功能要强一些
1. 首先我是在springBoot项目里写的,最开始在yml文件中配置一下
freemarker:
cache: false #关闭模板缓存,方便测试
template_update_dalay: 0 #检查模板更新延迟时间,设置为0表示立即检查,如果时间大于0会有缓存不方便进行模板测试
2.在配置文件的文件夹里建一个名为 templates 的包
用来存放freemarker中的模板文件,好像freemarker会自己在这个包里找模板文件 模板文件是以 ftl 作为后缀
目前就写到了map遍历,就直接拿来记录下吧
test1.ftl
<!DOCTYPE html>
<html>
<head>
<meta charset="utf‐8">
<title>Hello World!</title>
</head>
<body>
<#--注释 -->
Hello ${name}!
<br>
遍历list中的数据 数据模型中的名称为stus
<br>
<table>
<tr>
<td>序号</td>
<td>姓名</td>
<td>年龄</td>
<td>金额</td>
<#-- <td>出生日期</td>-->
</tr>
list遍历语法格式 : 数据模型名 as 形参名
<#list stus as stu >
<tr>
<td>${stu_index + 1}</td>
<td>${stu.name}</td>
<td>${stu.age}</td>
<td>${stu.money}</td>
<#-- <td>${stu.birthday}</td>-->
</tr>
</#list>
</table>
<br>
遍历数据模型中间的stuMap(map数据)
<br>
姓名:${stuMap['stu1'].name}<br/>
年龄:${stuMap['stu1'].age}<br/>
姓名:${stuMap.stu1.name}<br/>
年龄:${stuMap.stu1.age}<br/>
<br>
遍历map中的key stuMap?keys就是key列表(是一个list)<br>
<#list stuMap?keys as k>
${k}<br>
姓名:${stuMap[k].name}<br/>
年龄:${stuMap[k].age}<br/>
</#list>
</body>
</html>
3.后端接口部分
package com.xuecheng.test.freemarker.controller; import com.xuecheng.test.freemarker.model.Student; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.*; @RequestMapping("/freemarker") @Controller //不能使用@RestController,要输出HTML页面,使用@RestController输出的是JSON数据 public class FreeMarkerController { //测试1 @RequestMapping("/test1") public String test1(Map<String,Object> map){ //map就是freemarker模板使用的数据 map.put("name","test1"); Student stu1 = new Student(); stu1.setName("小明"); stu1.setAge(18); stu1.setMoney(1000.86f); stu1.setBirthday(new Date()); Student stu2 = new Student(); stu2.setName("小红"); stu2.setMoney(200.1f); stu2.setAge(19); // stu2.setBirthday(new Date()); List<Student> friends = new ArrayList<>(); friends.add(stu1); stu2.setFriends(friends); stu2.setBestFriend(stu1); List<Student> stus = new ArrayList<>(); stus.add(stu1); stus.add(stu2); //向数据模型放数据 map.put("stus",stus); //准备map数据 HashMap<String,Student> stuMap = new HashMap<>(); stuMap.put("stu1",stu1); stuMap.put("stu2",stu2); //向数据模型放数据 map.put("stu1",stu1); //向数据模型放数据 map.put("stuMap",stuMap); //返回模板文件名称 //返回free marker模板的位置,基于resources/templates路径 return "test1"; } //测试2 //测试3 }
补充:student模型类我用了lombok
student.java
import lombok.Data; import lombok.ToString; import java.util.Date; import java.util.List; @Data @ToString public class Student { private String name;//姓名 private int age;//年龄 private Date birthday;//生日 private Float money;//钱包 private List<Student> friends;//朋友列表 private Student bestFriend;//最好的朋友 }
最后:运行后的结果

难产难产难产

浙公网安备 33010602011771号