(五)Freemarker 整合Spring
来源:互联网 发布:排序算法及时间复杂度 编辑:程序博客网 时间:2024/05/17 03:20
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">
-
-
- <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 {
-
-
- @Autowired
- private FreeMarkerConfigurer springFreemarkerCfg;
-
-
- private Configuration freeMarkerCfg;
-
- @Test
- public void test() throws Exception{
-
- freeMarkerCfg = springFreemarkerCfg.getConfiguration();
-
-
- Template template = freeMarkerCfg.getTemplate("spring.freemarker.ftl");
-
-
- Map<String,Object> root = new HashMap<>();
- root.put("time", new Date());
-
-
- StringWriter writer = new StringWriter();
- template.process(root, writer);
- String content = writer.getBuffer().toString();
-
- System.out.println("content:" + content);
- }
- }