freemarker

一、快速入门

(一)、创建工程

freemarker-demo

引入依赖


        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-starter-freemarker
        

        
            org.springframework.boot
            spring-boot-starter-test
        
        
        
            org.projectlombok
            lombok
        

        
        
            org.apache.commons
            commons-io
            1.3.2
        
    

(二)、配置文件

application.yml

server:
  port: 8881 #服务端口
spring:
  application:
    name: freemarker-demo #指定服务名
  freemarker:
    cache: false  #关闭模板缓存,方便测试
    settings:
      template_update_delay: 0 #检查模板更新延迟时间,设置为0表示立即检查,如果时间大于0会有缓存不方便进行模板测试
    suffix: .ftl               #指定Freemarker模板文件的后缀名
    template-loader-path: classpath:/templates  #模板所在目录

(三)、创建模型类

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

package com.heima.freemarker.entity;
​
import lombok.Data;
​
import java.util.Date;
​
@Data
public class Student {
    private String name;//姓名
    private int age;//年龄
    private Date birthday;//生日
    private Float money;//钱包
}

(四)、创建模板

在resources下创建templates,此目录为freemarker的默认模板存放目录。

在templates下创建模板文件 01-basic.ftl ,模板中的插值表达式最终会被freemarker替换成具体的数据。




    
    Hello World!


普通文本 String 展示:

Hello ${name}

对象Student中的数据展示:
姓名:${stu.name}
年龄:${stu.age}

(五)、创建controller

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

package com.xuecheng.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;
​
@Controller
public class HelloController {
​
    @GetMapping("/basic")
    public String test(Model model) {
​
​
        //1.纯文本形式的参数
        model.addAttribute("name", "freemarker");
        //2.实体类相关的参数
        
        Student student = new Student();
        student.setName("小明");
        student.setAge(18);
        model.addAttribute("stu", student);
​
        return "01-basic";
    }
}

(六)、创建启动类

package com.heima.freemarker;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

(七)、测试

请求:http://localhost:8881/basic

freemarker_第1张图片

二、指令和语法

(一)、基础语法和种类

1、注释,即<#-- -->,介于其之间的内容会被freemarker忽略

<#--我是一个freemarker注释-->

2、插值(Interpolation):即 ${..} 部分,freemarker会用真实的值代替${..}

Hello ${name}

3、FTL指令:和HTML标记类似,名字前加#予以区分,Freemarker会解析标签中的表达式或逻辑。

<# >FTL指令 

4、文本,仅文本信息,这些不是freemarker的注释、插值、FTL指令的内容会被freemarker忽略解析,直接输出内容。

<#--freemarker中的普通文本-->
我是一个普通的文本

1、集合指令(List和Map)

    <#list stus as stu>
        
            ${stu_index+1}
            ${stu.name}
            ${stu.age}
            ${stu.money}
        
    
方式一:通过map['keyname'].property
输出stu1的学生信息:
姓名:${stuMap['stu1'].name}
年龄:${stuMap['stu1'].age}

方式二:通过map.keyname.property
输出stu2的学生信息:
姓名:${stuMap.stu2.name}
年龄:${stuMap.stu2.age}

    <#list stuMap?keys as key >
        
            ${key_index}
            ${stuMap[key].name}
            ${stuMap[key].age}
            ${stuMap[key].money}
        
    

2、判断(if)

    <#list stus as stu >
        <#if stu.name='小红'>
            
                ${stu_index}
                ${stu.name}
                ${stu.age}
                ${stu.money}
            
            <#else >
            
                ${stu_index}
                ${stu.name}
                ${stu.age}
                ${stu.money}
            
        
    

在freemarker中,=和==是一样的 

3、运算符

比较运算符

  • =或者==:判断两个值是否相等.

  • !=:判断两个值是否不等.

  • >或者gt:判断左边值是否大于右边值

  • >=或者gte:判断左边值是否大于等于右边值

  • <或者lt:判断左边值是否小于右边值

  • <=或者lte:判断左边值是否小于等于右边值

比较运算符注意

  • =!=可以用于字符串、数值和日期来比较是否相等

  • =!=两边必须是相同类型的值,否则会产生错误

  • 字符串 "x""x ""X"比较是不等的.因为FreeMarker是精确比较

  • 其它的运行符可以作用于数字和日期,但不能作用于字符串

  • 使用gt等字母运算符代替>会有更好的效果,因为 FreeMarker会把>解释成FTL标签的结束字符

  • 可以使用括号来避免这种情况,如:<#if (x>y)>

4、空值处理

(1)、判断某变量是否存在使用 “??”

用法为:variable??,如果该变量存在,返回true,否则返回false

例:为防止stus为空报错可以加上判断如下:

    <#if stus??>
    <#list stus as stu>
        ......
    
    
(2)、缺失变量默认值使用 “!”
  • 使用!要以指定一个默认值,当变量为空时显示默认值

    例: ${name!''}表示如果name为空显示空字符串。

  • 如果是嵌套对象则建议使用()括起来

    例: ${(stu.bestFriend.name)!''}表示,如果stu或bestFriend或name为空默认显示空字符串。

5、内建函数

(1)、集合的大小
${集合名?size}
(2)、日期格式化
显示年月日: ${today?date}

显示时分秒:${today?time}

显示日期+时间:${today?datetime}

自定义格式化: ${today?string("yyyy年MM月")}
(3)、内建函数c

model.addAttribute("point", 102920122);

point是数字型,使用${point}会显示这个数字的值,每三位使用逗号分隔。

如果不想显示为每三位分隔的数字,可以使用c函数将数字型转成字符串输出

${point?c}

(4)、将json字符串转成对象

一个例子:

其中用到了 assign标签,assign的作用是定义一个变量。

<#assign text="{'bank':'工商银行','account':'10101920201920212'}" />
<#assign data=text?eval />
开户行:${data.bank}  账号:${data.account}

你可能感兴趣的:(spring,cloud,java)