概述
模板引擎,基于模板和要改变的数据,生成输出文本(HTML网页,电子邮件,配置文件),是一个Java类库。
模板+数据=页面
搭建
导入jar坐标
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.20</version>
</dependency>
<!--解决freeMarker配置templateLoaderPath报错-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.0.4.RELEASE</version>
</dependency>
在spring-mvc.xml中配置freeMarker
<!-- freeMarker配置 -->
<bean id="freeMarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<!-- 增加自定义property -->
<property name="templateLoaderPath" value="/WEB-INF/views"/>
<property name="defaultEncoding" value="UTF-8"/>
<!--模板设置-->
<property name="freemarkerSettings">
<props>
<prop key="template_update_delay">0</prop><!--刷新模板的周期,单位为秒-->
<!-- <prop key="default_encoding">UTF-8</prop><!–模板的编码格式-->
<prop key="locale">zh_CN</prop><!--本地化设置-->
<prop key="number_format">0.######</prop>
</props>
</property>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="cache" value="false"/>
<property name="suffix" value=".ftl"/>
<property name="requestContextAttribute" value="rc"/>
<property name="contentType" value="text/html;charset=UTF-8"/>
<property name="order" value="0"/>
</bean>
controller层调用页面
在.ftl
视图文件中显示
访问http://localhost:8081/f01/init
即可显示
在freemarker中,所有的html标签、css、js都适用
数据类型
布尔型
直接输出${msg}
会报错
日期型
数值型
字符型
直接输出不存在的值或者null都会报错
sequence类型
hash类型
常见指令
assign
定义变量
if...else if...else
逻辑判断
list遍历指令
自定义指令macro
num*num乘法表
占位符指令nested
可将自定义指令中的内容通过占位符显示
import
引入其他文件中的宏
include
包含指令
页面静态化
页面上有很多不易改变的数据,就不能每次向后端请求,所以就将数据嵌套在一个模板当中