FreeMarker模板的使用
1.获取简单数据
使用EL表达式,${param}直接获取定义在freemarker中的简单数据
2.获取包装数据类型
${user.uName}直接获取定义在freemarker中包装数据类型数据
3.获取集合/数组数据类型
例子: List<User> userList=new ArrayList<User>();
<#list userList as user>
${user.uName}
</#list>
4.获取当前迭代的索引
List<User> userList=new ArrayList<User>()
<#list userList as user>
${user_index}
</#list>
5.逻辑判断
<#if 判断条件>
<#else>
</#if>
逻辑运算符(== != || &&)
6.日期类型格式化
1:date类型
${currTime?date}
2:datetime类型
${currTime?datetime}
3:time类型
${currTime?time}
4:自定义类型
${currTime?string("yyyy-MM-dd HH:mm:ss")}
7.处理空值(null)
对于需要放入freemarker中的数据如果存在是null(空值)的情况
1.将空值变成空串
${val!} //其实这里${val!"我是空串"}
2.采用默认值代替空值
${val!"w我只默认值"}
3.通过条件判断,动态输出
<#if currTime ??>
当前日期:${currTime?string("yyyy/MM/dd HH:mm:ss")}
<#else>
currrTime属性为null
</#if>
8.引入其他页面到本页面
<#include "/html/other.html">
FreeMarker和Spring框架的整合
1.引入freemarker的依赖
<!--freemarker的依赖-->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
</dependency>
<!-- 需要包含Spring上下文的支持 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.1.3.RELEASE</version>
</dependency>
2.在spring中配置freemarker
<!--freemarker for generator static page -->
<bean name="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/ftl/" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
3.freemarker的使用
@Test
public void testFreemarker() throws IOException, TemplateException {
//freemarker proj no need to depend on web container,so that you can build a java file to run it
//create configuration object for the freemarker
Configuration config=new Configuration(Configuration.getVersion());
//tould the configuration where is the ftl template files
config.setDirectoryForTemplateLoading(new File("D:\\Myself\\ftl"));
//set encoding
config.setDefaultEncoding("UTF-8");
//specify the file name of the template file
Template template = config.getTemplate("first.ftl");
//create the template file's data list
Map dataList=new HashMap<>();
dataList.put("firstTitle", "FirstFreemarker");
dataList.put("welcome", "Hello Freemarker");
//create a write object to specify file path for the generated file
Writer writer=new FileWriter(new File("D:\\Myself\\Html\\hello.html"));
//call the template object process function and to params is need
template.process(dataList, writer);
//flush the data steam and close writer steam
writer.flush();
writer.close();
}