栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java > SpringBoot

springboot整合Freemark模板(修订-详尽版)

SpringBoot 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot整合Freemark模板(修订-详尽版)

本篇是SpringBoot项目实战(3):整合Freemark模板一文的修订版,本文使用示例详细介绍、演示了freemarker常用的语法,以及如何通过freemarker生成纯静态的html。

本文知识点:

  1. springboot如何集成freemarker模板引擎
  2. 详细版:常用的freemarker语法
  3. 特别篇:如何在springboot中通过freemarker生成静态html(纯静态化)

想了解freemarker?没有比这篇文章更详细的了

springboot如何集成freemarker模板引擎

添加依赖

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


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

配置属性文件
# 是否允许HttpServletRequest属性覆盖(隐藏)控制器生成的同名模型属性。
spring.freemarker.allow-request-override=false
# 是否允许HttpSession属性覆盖(隐藏)控制器生成的同名模型属性。
spring.freemarker.allow-session-override=false
# 是否启用模板缓存。
spring.freemarker.cache=false
# 模板编码。
spring.freemarker.charset=UTF-8
# 是否检查模板位置是否存在。
spring.freemarker.check-template-location=true
# Content-Type value.
spring.freemarker.content-type=text/html
# 是否启用freemarker
spring.freemarker.enabled=true
# 设定所有request的属性在merge到模板的时候,是否要都添加到model中.
spring.freemarker.expose-request-attributes=false
# 是否在merge模板的时候,将HttpSession属性都添加到model中
spring.freemarker.expose-session-attributes=false
# 设定是否以springMacroRequestContext的形式暴露RequestContext给Spring’s macro library使用
spring.freemarker.expose-spring-macro-helpers=true
# 是否优先从文件系统加载template,以支持热加载,默认为true
spring.freemarker.prefer-file-system-access=true
# 设定模板的后缀.
spring.freemarker.suffix=.ftl
# 设定模板的加载路径,多个以逗号分隔,默认: 
spring.freemarker.template-loader-path=classpath:/templates/
# 设定FreeMarker keys.
spring.freemarker.settings.template_update_delay=0
spring.freemarker.settings.default_encoding=UTF-8
spring.freemarker.settings.classic_compatible=true

编写Controller
@Controller
public class FreemarkController {

    @RequestMapping("/")
    public String index(Model model) {
 return "index";
    }
}

页面
 
 
 
	SpringBoot + Freemarker 
	 
 
 
	Hello boy,

当前时间:${.now?string("yyyy-MM-dd HH:mm:ss.sss")}

常用的freemarker语法

下面详细介绍在ftl模板中如何使用列表、map、字符串、数字、日期、switch以及macro宏指令等语法。

修改下controller,传递一些需要处理的参数

@RequestMapping("/")
public String index(Model model) {
	Map map = new linkedHashMap<>();
	for (int i = 0; i < 5; i++) {
		map.put("key" + i, "value" + i);
	}
	model.addAttribute("list", Arrays.asList("string1", "string2", "string3", "string4", "string5", "string6"));
	model.addAttribute("map", map);
	model.addAttribute("name", "   htTps://wWw.zHyD.mE   ");
	model.addAttribute("htmlText", "html内容");
	model.addAttribute("num", 123.012);
	model.addAttribute("null", null);
	model.addAttribute("dateObj", new Date());
	model.addAttribute("bol", true);
	return "index";
}

重写index.ftl

 


    Freemarker 语法大全
    
    
 html {
     font-size: 14px;
     font-weight: 400;
 }
 .exp {
     font-size: 12px;
     color: lightgray;
 }
    


当前时间:${.now?string("yyyy-MM-dd HH:mm:ss.sss")}

list长度:${list?size}
列表
<#list list as item>
${item }, 索引:${item_index },hasNext:${item_has_next}
数字遍历
<#list 1..3 as item>
数字${item}
map
<#list map?keys as key>
${map[key]}, 索引:${key_index },hasNext:${key_has_next}
字符串
普通字符串:${name}
非html编码:${htmlText}
html编码:${htmlText?html}
首字母大写:${name?cap_first}
首字母小写:${name?uncap_first}
全小写:${name?lower_case}
全大写:${name?upper_case}
去除首位空格:${name?trim}
空字符串:${null?if_exists}
是否包含某个字符串:${name?contains("wWw")?string}
默认值:${null?default("空值默认")}
“${name}”字符串长度:${name?length}
定义字符串:str=码一码<#assign str="码一码"/>
字符串拼接(1):${"字符串拼接 + " + str}
字符串拼接(2):${"字符串拼接 + ${str}"}
字符串截取单个字符(1):${str[1]}
字符串截取(2):${str?substring(1)}
字符串截取(3):${str?substring(1,2)}
indexOf:${str?index_of("一")}
split分割字符串: <#list "a|b|c"?split("|") as item> ${item}
if...elseif...else: <#if null == ''> 匹配if显示 <#elseif null == '1'> 匹配elseif显示 <#else> 匹配else显示
switch
<#switch str> <#case "你好"> 匹配“你好” <#break > <#case "码一码"> 匹配“码一码” <#break > <#default> 默认匹配
数字
普通数字:${num}
数字类型:${num?string.number}
货币类型:${num?string.currency}
百分比类型:${num?string.percent}
格式化数字:${num?string("#.###")}
取数字的整数部分:${num?int}
运算符
不等于:!= 例如:${(1 != 2)?string('1 != 2', '1 == 2')}
等于:== 例如:${(1 == 1)?string('1 == 1', '1 != 1')}
大于(1):> 例如:${(2 > 1)?string('2 > 1', '2 < 1')}。注:使用> 时必须加括号,否则可能会被当成普通的标签闭合符号而引起报错
大于(2):gt 例如:${(2 gt 1)?string('2 gt 1', '2 lte 1')}
大于等于:gte 例如:${(2 gte 2)?string('2 gte 2', '2 lt 2')}
小于(1):< 例如:${(1 < 2)?string('1 < 2', '1 > 2')}。注:使用< 时必须加括号,否则可能会被当成普通的标签闭合符号而引起报错
小于(2):lt 例如:${(1 lt 2)?string('1 lt 2', '1 gte 2')}
小于等于:lte 例如:${(2 lte 2)?string('2 lte 2', '2 gt 2')}
boolean
普通boolean输出:${bol}
boolean判断输出:${bol?string('true的时候显示','false的时候显示')}
日期
${dateObj?date}
${dateObj?time}
${dateObj?string("yyyy-MM-dd HH:mm:ss.SSS")}
import
<#import "import.ftl" as importObj>

${importObj.importStr}

${importObj.importStr1}

macro宏模板
<#macro listMacro title items>

${title?cap_first}:

    <#list items as item>
  • ${item?cap_first}
<#nested >
<@listMacro items=["item1", "item2", "item3"] title="Items"> nested标签表示可以插入自定义的内容
 include  <#include "eclipse.ftl">

通过freemarker生成静态html

首先需要编写一个可以在普通类中获取到springbean的工具类SpringContextHolder

@Component
public class SpringContextHolder implements ApplicationContextAware {

    private static ApplicationContext appContext = null;

    
    public static Object getBean(String name) {
 return appContext.getBean(name);

    }

    
    public static  T getBean(Class clazz) {
 return appContext.getBean(clazz);
    }

    
    public static  T getBean(String name, Class clazz) {
 return appContext.getBean(name, clazz);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
 if (appContext == null) {
     appContext = applicationContext;
 }
    }
}

然后编写一个生成静态html文件的工具类FreemarkerUtil

public class FreemarkerUtil {

    public static String parseTpl(String viewName, Map params) {
 Configuration cfg = SpringContextHolder.getBean(Configuration.class);
 String html = null;
 Template t = null;
 try {
     t = cfg.getTemplate(viewName + ".ftl");
     html = FreeMarkerTemplateUtils.processTemplateIntoString(t, params);
 } catch (IOException | TemplateException e) {
     e.printStackTrace();
 }
 return html;
    }
}

为了方便查看, 添加一个mapping

@RequestMapping("/createHtml")
@ResponseBody
public String createHtml(Model model){
	Map map = new linkedHashMap<>();
	for (int i = 0; i < 5; i++) {
		map.put("key" + i, "value" + i);
	}
	model.addAttribute("list", Arrays.asList("string1", "string2", "string3", "string4", "string5", "string6"));
	model.addAttribute("map", map);
	model.addAttribute("name", "   htTps://wWw.zHyD.mE   ");
	model.addAttribute("htmlText", "html内容");
	model.addAttribute("num", 123.012);
	model.addAttribute("null", null);
	model.addAttribute("dateObj", new Date());
	model.addAttribute("bol", true);
	return FreemarkerUtil.parseTpl("index", model.asMap());
}

ok,访问/createHtml

到此为止,本篇已详细介绍了freemarker的使用方法。

还是那句话

我可以对一个人无限的好,前提是值得。 ——慕冬雪

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/235065.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号