Freemarker1.0

Freemarker

需要创建Spring Boot+Freemarker工程用于测试模板。需要创建Spring Boot+Freemarker工程用于测试模板。

创建测试工程

创建一个freemarker 的测试工程专门用于freemarker的功能测试与模板的测试。

pom.xml如下

<?xml version="1.0" encoding="UTF‐8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema‐instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven‐4.0.0.xsd">
<parent>
<artifactId>xc‐framework‐parent</artifactId>
<groupId>com.xue</groupId>
<version>1.0‐SNAPSHOT</version>
<relativePath>../xc‐framework‐parent/pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>test‐freemarker</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring‐boot‐starter‐freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons‐io</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring‐boot‐starter‐test</artifactId>
</dependency>
</dependencies>
</project>

配置文件

配置application.yml和 logback-spring.xml,从cms工程拷贝这两个文件,进行更改, logback-spring.xml无需更
改,application.yml内容如下:

server:
	port: 8088 #服务端口
spring:
	application:
		name: test‐freemarker #指定服务名
	freemarker:
		cache: false #关闭模板缓存,方便测试
		settings:
			template_update_delay: 0 #检查模板更新延迟时间,设置为0表示立即检查,如果时间大于0会有缓存不方便进行模板测试

创建模板

在 src/main/resources下创建templates,此目录为freemarker的默认模板存放目录。
在templates下创建模板文件test1.ftl,模板中的${name}最终会被freemarker替换成具体的数据。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf‐8">
<title>Hello World!</title>
</head>
<body>
Hello ${name}!
</body>
</html>

创建controller

创建Controller类,向Map中添加name,最后返回模板文件

package com.xue.test.freemarker.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;
import java.util.Map;
@RequestMapping("/freemarker")
@Controller
public class FreemarkerController {
@Autowired
RestTemplate restTemplate;
@RequestMapping("/test1")
public String freemarker(Map<String, Object> map){
map.put("name","员");
//返回模板文件名称
return "test1";
}
}

创建启动类

创建启动类

@SpringBootApplication
public class FreemarkerTestApplication {
public static void main(String[] args) {
SpringApplication.run(FreemarkerTestApplication.class,args);
}
}

测试

请求:http://localhost:8088/freemarker/test1

补充

在freemarker的测试工程下创建模型类型用于测试

package com.cg.pojo;

import java.util.Date;
import java.util.List;
import java.util.Objects;

public class Student {

    private String name;
    private Integer age;
    private Date birthday;
    private Float money;
    private List<Student> friends;
    private Student bestFriend;

    public Student() {
    }

    public Student(String name, Integer age, Date birthday, Float money, List<Student> friends, Student bestFriend) {
        this.name = name;
        this.age = age;
        this.birthday = birthday;
        this.money = money;
        this.friends = friends;
        this.bestFriend = bestFriend;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public Float getMoney() {
        return money;
    }

    public void setMoney(Float money) {
        this.money = money;
    }

    public List<Student> getFriends() {
        return friends;
    }

    public void setFriends(List<Student> friends) {
        this.friends = friends;
    }

    public Student getBestFriend() {
        return bestFriend;
    }

    public void setBestFriend(Student bestFriend) {
        this.bestFriend = bestFriend;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", birthday=" + birthday +
                ", money=" + money +
                ", friends=" + friends +
                ", bestFriend=" + bestFriend +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return Objects.equals(name, student.name) &&
                Objects.equals(age, student.age) &&
                Objects.equals(birthday, student.birthday) &&
                Objects.equals(money, student.money) &&
                Objects.equals(friends, student.friends) &&
                Objects.equals(bestFriend, student.bestFriend);
    }

    @Override
    public int hashCode() {

        return Objects.hash(name, age, birthday, money, friends, bestFriend);
    }
}

package com.cg.web;

import com.cg.pojo.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RequestMapping("/freemarker")
@Controller
public class TestFreemarkerController {

    @RequestMapping("/test")
    public String testFreemarker(Map<String,Object> map){
        map.put("name","科技");
        //返回模板文件名称
        return "testfreemarker";
    }

    @RequestMapping("/test1")
    public String testFreemarker1(Map<String,Object> map){
        Student student = new Student();
        student.setName("小小");
        student.setAge(18);
        student.setMoney(10000.33f);
        student.setBirthday(new Date());

        List<Student> studentList = new ArrayList<>();
        studentList.add(student);

        Student student1 = new Student();
        student1.setName("许文");
        student1.setAge(28);
        student1.setBirthday(new Date());
        student1.setMoney(10000.23f);
        student1.setFriends(studentList);
        student1.setBestFriend(student);

        List<Student> stus = new ArrayList<>();
        stus.add(student1);

        map.put("stus",stus);
        map.put("student2",student1);

        return "index";
    }

}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>测试ferrmarker1</title>
</head>
<body>
    <h1 style="color: red">${student2.name}</h1>
    <table>
        <tr>
            <td>姓名</td>
            <td>年龄</td>
            <td>出生日期</td>
            <td>钱包</td>
            <td>最好的朋友</td>
            <td>朋友个数</td>
            <td>朋友列表</td>
        </tr>
         <#if stus??>
             <#list stus as stu>
                <tr>
                    <td>${stu.name!''}</td>
                    <td>${stu.age}</td>
                    <td>${(stu.birthday?date)!''}</td>
                    <td>${stu.money}</td>
                    <td>${stu.bestFriend.name}</td>
                    <td>${(stu.friends?size)!0}</td>
                    <td>
                        <#if stu.friends??>
                            <#list stu.friends as friend>
                                ${friend.name!''}
                                ${friend.age!''}
                                ${friend.money!''}
                                ${friend.bestFriend!''}
                                ${friend.friends!''}
                            </#list>
                        </#if>
                    </td>
                </tr>
             </#list>
         </#if>
    </table>



</body>
</html>

使用模板文件静态化

//基于模板生成静态化文件
@Test
public void testGenerateHtml() throws IOException, TemplateException {
	//创建配置类
	Configuration configuration=new Configuration(Configuration.getVersion());
    //设置模板路径
    String classpath = this.getClass().getResource("/").getPath();
    configuration.setDirectoryForTemplateLoading(new File(classpath + "/templates/"));
    //设置字符集
    configuration.setDefaultEncoding("utf‐8");
    //加载模板
    Template template = configuration.getTemplate("test1.ftl");
    //数据模型
    Map<String,Object> map = new HashMap<>();
    map.put("name","员");
    //静态化
    String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
    //静态化内容
    System.out.println(content);
    InputStream inputStream = IOUtils.toInputStream(content);
    //输出文件
    FileOutputStream fileOutputStream = new FileOutputStream(new File("d:/test1.html"));
    int copy = IOUtils.copy(inputStream, fileOutputStream);
}

使用模板字符串静态化

//基于模板字符串生成静态化文件
@Test
public void testGenerateHtmlByString() throws IOException, TemplateException {
    //创建配置类
    Configuration configuration=new Configuration(Configuration.getVersion());
    //模板内容,这里测试时使用简单的字符串作为模板
    String templateString="" +
    "<html>\n" +
    " <head></head>\n" +
    " <body>\n" +
    " 名称:${name}\n" +
    " </body>\n" +
    "</html>";
    //模板加载器
    StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
    stringTemplateLoader.putTemplate("template",templateString);
    configuration.setTemplateLoader(stringTemplateLoader);
    //得到模板
    Template template = configuration.getTemplate("template","utf‐8");
    //数据模型
    Map<String,Object> map = new HashMap<>();
    map.put("name","员");
    //静态化
    String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
    //静态化内容
	System.out.println(content);
    InputStream inputStream = IOUtils.toInputStream(content);
    //输出文件
    FileOutputStream fileOutputStream = new FileOutputStream(new File("d:/test1.html"));
    IOUtils.copy(inputStream, fileOutputStream);
}

新增map.putAll(body)和map.put(“model”,body)前端取值方法

java代码

//课程详情页面测试
    @GetMapping("/course")
    public String  course(Map<String,Object> map){
        ResponseEntity<Map> forEntity = restTemplate.getForEntity("http://localhost:31200/course/courseview/4028e581617f945f01617f9dabc40000", Map.class);
        Map body = forEntity.getBody();
        //设置模型数据
        //map.putAll(body);
        map.put("model",body);
        return "course";
    }
   

实体类json值

{
  "courseBase": {
    "id": "4028e581617f945f01617f9dabc40000",
    "name": "Bootstrap开发框架",
    "users": "",
    "mt": "1-1",
    "st": "1-1-1",
    "grade": "200002",
    "studymodel": "201001",
    "teachmode": null,
    "description": "Bootstrap是由Twitter推出的一个前台页面开发框架,在行业之中使用较为广泛。此开发框架包含了大量的CSS、JS程序代码,可以帮助开发者(尤其是不擅长页面开发的程序人员)轻松的实现一个不受浏览器限制的精美界面效果。",
    "status": "202002",
    "companyId": "1",
    "userId": null
  },
  "courseMarket": {
    "id": "4028e581617f945f01617f9dabc40000",
    "charge": "203002",
    "valid": "204001",
    "qq": "4455432",
    "price": 0.01,
    "price_old": null,
    "startTime": "2018-04-01T02:50:31.000+0000",
    "endTime": "2020-04-01T02:50:37.000+0000"
  },
  "coursePic": {
    "courseid": "4028e581617f945f01617f9dabc40000",
    "pic": "group1/M00/00/01/wKhlQFqO0OGAFyhGAAA-8SWa8Qc537.jpg"
  },
  "teachplanNode": {
    "id": "1",
    "pname": "Bootstrap开发框架",
    "parentid": null,
    "grade": null,
    "ptype": null,
    "description": null,
    "courseid": null,
    "status": null,
    "orderby": null,
    "timelength": null,
    "trylearn": null,
    "children": [
      {
        "id": "2",
        "pname": "计算机原理",
        "parentid": null,
        "grade": null,
        "ptype": null,
        "description": null,
        "courseid": null,
        "status": null,
        "orderby": null,
        "timelength": null,
        "trylearn": null,
        "children": [
          {
            "id": "3",
            "pname": "计算机硬件",
            "parentid": null,
            "grade": null,
            "ptype": null,
            "description": null,
            "courseid": null,
            "status": null,
            "orderby": null,
            "timelength": null,
            "trylearn": null,
            "children": null
          },
          {
            "id": "4",
            "pname": "计算机软件",
            "parentid": null,
            "grade": null,
            "ptype": null,
            "description": null,
            "courseid": null,
            "status": null,
            "orderby": null,
            "timelength": null,
            "trylearn": null,
            "children": null
          }
        ]
      },
      {
        "id": "40289981704491930170449557690000",
        "pname": "测试课程",
        "parentid": null,
        "grade": null,
        "ptype": null,
        "description": null,
        "courseid": null,
        "status": null,
        "orderby": null,
        "timelength": null,
        "trylearn": null,
        "children": [
          {
            "id": "4028998170449193017044958d2e0001",
            "pname": "测试课程",
            "parentid": null,
            "grade": null,
            "ptype": null,
            "description": null,
            "courseid": null,
            "status": null,
            "orderby": null,
            "timelength": null,
            "trylearn": null,
            "children": null
          },
          {
            "id": "402899817044919301704496b47a0003",
            "pname": "测试课程1",
            "parentid": null,
            "grade": null,
            "ptype": null,
            "description": null,
            "courseid": null,
            "status": null,
            "orderby": null,
            "timelength": null,
            "trylearn": null,
            "children": null
          },
          {
            "id": "402899817044919301704496056e0002",
            "pname": "测试课程",
            "parentid": null,
            "grade": null,
            "ptype": null,
            "description": null,
            "courseid": null,
            "status": null,
            "orderby": null,
            "timelength": null,
            "trylearn": null,
            "children": null
          }
        ]
      },
      {
        "id": "5",
        "pname": "计算机编程入门",
        "parentid": null,
        "grade": null,
        "ptype": null,
        "description": null,
        "courseid": null,
        "status": null,
        "orderby": null,
        "timelength": null,
        "trylearn": null,
        "children": [
          {
            "id": "6",
            "pname": "java语法介绍",
            "parentid": null,
            "grade": null,
            "ptype": null,
            "description": null,
            "courseid": null,
            "status": null,
            "orderby": null,
            "timelength": null,
            "trylearn": null,
            "children": null
          },
          {
            "id": "7",
            "pname": "Hello World",
            "parentid": null,
            "grade": null,
            "ptype": null,
            "description": null,
            "courseid": null,
            "status": null,
            "orderby": null,
            "timelength": null,
            "trylearn": null,
            "children": null
          }
        ]
      },
      {
        "id": "4028e581617ce7b601617ce801790000",
        "pname": "数据库编程",
        "parentid": null,
        "grade": null,
        "ptype": null,
        "description": null,
        "courseid": null,
        "status": null,
        "orderby": null,
        "timelength": null,
        "trylearn": null,
        "children": [
          {
            "id": "402885816347f814016348d68bad0000",
            "pname": "数据库基础知识",
            "parentid": null,
            "grade": null,
            "ptype": null,
            "description": null,
            "courseid": null,
            "status": null,
            "orderby": null,
            "timelength": null,
            "trylearn": null,
            "children": null
          },
          {
            "id": "402885816347f814016348d6c5920001",
            "pname": "SQL查询",
            "parentid": null,
            "grade": null,
            "ptype": null,
            "description": null,
            "courseid": null,
            "status": null,
            "orderby": null,
            "timelength": null,
            "trylearn": null,
            "children": null
          },
          {
            "id": "402885816347f814016348d7153c0002",
            "pname": "SQL优化",
            "parentid": null,
            "grade": null,
            "ptype": null,
            "description": null,
            "courseid": null,
            "status": null,
            "orderby": null,
            "timelength": null,
            "trylearn": null,
            "children": null
          }
        ]
      },
      {
        "id": "8",
        "pname": "操作系统原理",
        "parentid": null,
        "grade": null,
        "ptype": null,
        "description": null,
        "courseid": null,
        "status": null,
        "orderby": null,
        "timelength": null,
        "trylearn": null,
        "children": [
          {
            "id": "4028e58161bbcd350161bbcefe3d0001",
            "pname": "操作系统原理",
            "parentid": null,
            "grade": null,
            "ptype": null,
            "description": null,
            "courseid": null,
            "status": null,
            "orderby": null,
            "timelength": null,
            "trylearn": null,
            "children": null
          },
          {
            "id": "4028e581617d02e101617d070ed90000",
            "pname": "操作系统类型介绍",
            "parentid": null,
            "grade": null,
            "ptype": null,
            "description": null,
            "courseid": null,
            "status": null,
            "orderby": null,
            "timelength": null,
            "trylearn": null,
            "children": null
          }
        ]
      }
    ]
  }
}

map.putAll(body)取值方法

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Hello World!</title>
</head>
<body>
    
${courseBase.name}

</body>
</html>

map.put(“model”,body)取值方法

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Hello World!</title>
</head>
<body>

${model.courseBase.name}

</body>
</html>

parentid": null,
“grade”: null,
“ptype”: null,
“description”: null,
“courseid”: null,
“status”: null,
“orderby”: null,
“timelength”: null,
“trylearn”: null,
“children”: null
}
]
}
]
}
}


### map.putAll(body)取值方法

```html
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Hello World!</title>
</head>
<body>
    
${courseBase.name}

</body>
</html>

map.put(“model”,body)取值方法

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Hello World!</title>
</head>
<body>

${model.courseBase.name}

</body>
</html>

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值