依赖
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
配置
需要在spring-mvc的配置文件添加如下配置:
<!-- freemarker配置器 -->
<bean id="freemarkerConfigurer" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/ftl/"/><!-- 模板文件路径 -->
<property name="defaultEncoding" value="utf-8"/><!-- 字符集 -->
<property name="freemarkerSettings" ref="freemarkerConfiguration" /><!-- 读取配置文件 -->
<property name="freemarkerVariables">
<map>
<entry key="xml_escape" value-ref="fmXmlEscape" />
</map>
</property>
</bean>
<!-- freemarker配置 -->
<bean id="freemarkerConfiguration" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location" value="classpath:config/freemarker.properties"/>
</bean>
<!-- freemarker视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="cache" value="true"/><!-- 开启模板缓存 -->
<property name="suffix" value=".ftl"/><!-- 模板文件后缀 -->
<property name="contentType" value="text/html;charset=utf-8"/>
</bean>
<!-- 转义 -->
<bean id="fmXmlEscape" class="freemarker.template.utility.XmlEscape"/>
freemarker.properties的配置:
datetime_format=yyyy-MM-dd HH:mm:ss
date_format=yyyy-MM-dd
time_format=HH:mm:ss
boolean_format=true,false
whitespace_stripping=true
default_encoding=UTF-8
tag_syntax=auto_detect
url_escaping_charset=UTF-8
classic_compatible=true
template_update_delay=1
locale=zh_CN
number_format=\#0.\#\#\#\#\#
宏的使用
如下,可以定义一个宏
<#macro testMacro param1 param2>
<h1>I'm the html content created by the testMacro!</h1>
<br>
The param1 = ${param1}, and the param2 = ${param2}
<hr>
<#nested><!-- 这里输出标签体的内容 -->
</#macro>
在页面中就可以直接使用了:
<#import "/mymacro.ftl" as mymacro/>
<@mymacro.testMacro param1="我是param1" param2="我是param2">
我是中间的标签体内容
</@>