Freemarker 实现Html 静态化

本文内容:介绍了freemarker 渲染HTML 页面的几种方式:

  • 通过模板生成Html

  • 字符串静态化

  • 数据渲染

1

引入依赖

pom.xml

<dependency>      <groupId>org.springframework.boot</groupId>      <artifactId>spring-boot-starter-freemarker</artifactId></dependency><dependency>      <groupId>org.springframework.boot</groupId>      <artifactId>spring-boot-starter-web</artifactId></dependency>

2

编写实体类

user.java

public class User {  private String userName;  private String userPassword;  private int age;  public static List<User> initList(){    List<User> users=new ArrayList<User>();    users.add(new User("张三", "890123", 18));    users.add(new User("李四", "901234", 23));    users.add(new User("王五", "012345", 14));    users.add(new User("赵六", "123456", 30));    users.add(new User("田七", "234567", 32));    return users;  }  public User() {    super();  }  public User(String userName, String userPassword, int age) {    super();    this.userName = userName;    this.userPassword = userPassword;    this.age = age;  }}

3

编写模板文件

创建方式:新建Html页面,编写好后修改后缀为ftl 

存放路径:src/main/resources/template/htmlList.ftl

htmlList.ftl 

<!DOCTYPE html><html><head><meta charset="UTF-8">
<script type="text/javascript" src="static/js/jquery.min.js"></script>  <link href="static/bootstrap/css/bootstrap.min.css" rel="stylesheet">   <script src="static/bootstrap/js/bootstrap.min.js"></script>
<title>Freemarker</title></head><body>简单遍历list:<#list userList as user>  用户名:${user.userName}  密  码:${user.userPassword}  年  龄: ${user.age}</#list> <#--Freemarker遍历list并应用list隐含变量item_index-->item_index使用:<#list userList as user>第${user_index+1}个用户  用户名:${user.userName}  密  码:${user.userPassword}  年  龄: ${user.age}</#list>
<#--Freemarker遍历list并应用list隐含变量item_has_next-->item_has_next,size使用:<#list userList as user>  用户名:${user.userName}  密  码:${user.userPassword}  年  龄: ${user.age}  <#if !user_has_next>    共有${userList?size}最后一个用户是:${user.userName}</#if></#list>
<#--Freemarker遍历list并按用户年龄升序排序-->按用户年龄升序排序:<#list userList?sort_by("age") as user>  用户名:${user.userName}  密  码:${user.userPassword}  年  龄: ${user.age}</#list>
<#--Freemarker遍历list并按用户年龄降序排序-->按用户年龄降序排序:<#list userList?sort_by("age")?reverse as user>  用户名:${user.userName}  密  码:${user.userPassword}  年  龄: ${user.age} </#list>
<#--Freemarker遍历list当用户年龄大于21岁时,停止输出-->list中应用break:<#list userList?sort_by("age")?reverse as user>  用户名:${user.userName}  密  码:${user.userPassword}  年  龄: ${user.age}  <#if (user.age>21) >    <#break>  </#if></#list>
</body></html>

4

通过模板生成Html

绝对路径获取模板

@RequestMapping("absolutePath")  @ResponseBody  public String html() throws TemplateException, IOException {    // 第一步:创建一个Configuration对象,直接new一个对象。构造方法的参数就是freemarker对于的版本号。    Configuration configuration = new Configuration(Configuration.getVersion());    // 第二步:设置模板文件所在的路径。    configuration.setDirectoryForTemplateLoading(new File(        "D:\\E_softwareFiles\\Eclipse\\Springboot_newman\\freemarker\\src\\main\\resources\\template"));    // 第三步:设置模板文件使用的字符集。一般就是utf-8.    configuration.setDefaultEncoding("utf-8");    // 第四步:加载一个模板,创建一个模板对象。    Template template = configuration.getTemplate("htmlList.ftl");    // 第五步:创建一个模板使用的数据集,可以是pojo也可以是map。一般是Map。    Map dataModel = new HashMap<>();    // 向数据集中添加数据    List<User> users = User.initList();    dataModel.put("userList", users);    // 第六步:创建一个Writer对象,一般创建一FileWriter对象,指定生成的文件名。    Writer out = new FileWriter(new File(        "D:\\E_softwareFiles\\Eclipse\\Springboot_newman\\freemarker\\src\\main\\resources\\templates\\absolutePath.html"));    // 第七步:调用模板对象的process方法输出文件。    template.process(dataModel, out);    // 第八步:关闭流。    out.close();    return "Get";  }

相对路径获取模板

@RequestMapping("classPath")  @ResponseBody  public String testGenerateHtml() throws IOException, TemplateException, URISyntaxException {    // 创建配置类    Configuration configuration = new Configuration(Configuration.getVersion());    // 设置模板路径 toURI()防止路径出现空格    // /D:/E_softwareFiles/Eclipse/Springboot_newman/freemarker/target/classes/    String classpath = this.getClass().getResource("/").toURI().getPath();    System.out.println(classpath);    configuration.setDirectoryForTemplateLoading(new File(classpath + "/template/"));    // 设置字符集    configuration.setDefaultEncoding("utf-8");    // 加载模板    Template template = configuration.getTemplate("htmlList.ftl");    // 数据模型    Map dataModel = new HashMap<>();    List<User> users = User.initList();    dataModel.put("userList", users);    // 静态化    String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, dataModel);    // 打印静态化内容    System.out.println(content);    InputStream inputStream = IOUtils.toInputStream(content);    // 定位到项目路径    // /D:/E_softwareFiles/Eclipse/Springboot_newman/freemarker    String path=System.getProperty("user.dir");    System.out.println(path);    // 输出文件    FileOutputStream fileOutputStream = new FileOutputStream(new File(path + "/src/main/resources/templates/classPath.html"));    int copy = IOUtils.copy(inputStream, fileOutputStream);    return "It's OK";  }

这里两种方法的区别在于获取模板的方式:

  • 前者获取的是固定路径,一旦模板文件或项目位置发生变化就需要改动较多的地方;

  • 后者获取的是本项目下相应位置的模板文件,即使项目位置发生变化也无需改动代码。

5

字符串静态化

HtmlStringStatic.java

public class HtmlStringStatic {
  public static void main(String[] args) 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);      // 定位到项目路径      String path=System.getProperty("user.dir");    System.out.println(path);    // 输出文件      FileOutputStream fileOutputStream = new FileOutputStream(new File(path + "/src/main/resources/templates/stringStatic.html"));      int copy = IOUtils.copy(inputStream, fileOutputStream);  }}

6

数据渲染

HtmlRendering.java

@Controllerpublic class HtmlRendering {  // localhost:8080/freemarker/htmlRendering  @RequestMapping("htmlRendering")  public String rendering(Model model) {    List<User> users = User.initList();    model.addAttribute("userList", users);    return "rendering";  }}

在这里,rendering.ftl 是 htmlList.ftl 的复制,放在了

src/main/resources/templates 目录下,也就是springboot存放Html 页面的位置。

FreeMarkerProperties 中则配置了 Freemarker 的基本信息,例如模板位置在classpath:/templates/ ,模板后缀为 .ftl,这些配置我们都可以在 application.properties 中进行修改。

@ConfigurationProperties(prefix = "spring.freemarker")public class FreeMarkerProperties extends AbstractTemplateViewResolverProperties {        public static final String DEFAULT_TEMPLATE_LOADER_PATH = "classpath:/templates/";        public static final String DEFAULT_PREFIX = "";        public static final String DEFAULT_SUFFIX = ".ftl";        /**         * Well-known FreeMarker keys which are passed to FreeMarker's Configuration.         */        private Map<String, String> settings = new HashMap<>();}

7

测试

通过模板生成Html--绝对路径

absolutePath.html

通过模板生成Html--相对路径

classPath.html

字符串静态化

stringStatic.html

数据渲染

浏览器访问 localhost:8080/freemarker/htmlRendering

至此,本文结束。欢迎各位关注我的公众号:暗星涌动。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

暗星涌动

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值