Freemarker 可以和spring 进行无缝整合, 整合方式也非常简单。 Freemarker 在Web 应用中发送邮件中,做邮件模板是一个非常好的一个应用方式。
【1. 引入jar 包】
除了添加spring 的jar包以外,还需要添加 freemarker 的jar 包
【2. 添加配置】
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
- <!-- 配置spring 的freemarker引擎 -->
- <bean id="springFreemarkerCfg"
- class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
- <property name="templateLoaderPath" value="classpath:/templates" />
- <property name="freemarkerSettings">
- <props>
- <prop key="template_update_delay">0</prop>
- <prop key="default_encoding">UTF-8</prop>
- </props>
- </property>
- </bean>
- </beans>
【3. 测试用例】
- package org.zgf.learn.freemarker.spring;
- import java.io.StringWriter;
- import java.util.Date;
- import java.util.HashMap;
- import java.util.Map;
- import org.junit.Test;
- import org.junit.runner.RunWith;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.test.context.ContextConfiguration;
- import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
- import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
- import freemarker.template.Configuration;
- import freemarker.template.Template;
- @RunWith(SpringJUnit4ClassRunner.class)
- @ContextConfiguration(locations="classpath:org/zgf/learn/freemarker/spring/applications-freemarker.xml")
- public class Test_spring_freemarker {
- //1. 获取spring 的freeMarkerConfigurer 配置类
- @Autowired
- private FreeMarkerConfigurer springFreemarkerCfg;
- //Freemarker 原生的配置类型
- private Configuration freeMarkerCfg;
- @Test
- public void test() throws Exception{
- //2. 获取 freemarker:通过sprign 的FreeMarkerConfigurer Bean 来创建
- freeMarkerCfg = springFreemarkerCfg.getConfiguration();
- //3. 加载模板
- Template template = freeMarkerCfg.getTemplate("spring.freemarker.ftl");
- //4. 构造数据对象
- Map<String,Object> root = new HashMap<>();
- root.put("time", new Date());
- //5. 输出
- StringWriter writer = new StringWriter();
- template.process(root, writer);
- String content = writer.getBuffer().toString();
- System.out.println("content:" + content);
- }
- }