(五)Freemarker 整合Spring
2016-03-01 17:39
169 查看
Freemarker 可以和spring 进行无缝整合, 整合方式也非常简单。 Freemarker 在Web 应用中发送邮件中,做邮件模板是一个非常好的一个应用方式。
【1. 引入jar 包】
除了添加spring 的jar包以外,还需要添加 freemarker 的jar 包
【2. 添加配置】
【3. 测试用例】
【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); } }
相关文章推荐
- spring对AOP的支持 jdk和cglib
- 关于java的多态方法调用顺序的问题
- Java多线程(六)——Synchronized关键字
- java的List排序
- 扫描输入--来自《Java编程思想第四版》第13章
- 如何更改Eclipse的workspace路径
- eclipse中使用android ndk
- 【Java EE (Struts2 + Spring + Hibernate)开发】系列之 Spring(一)基本用法
- spring之spring mvc的DispatcherServlet
- java设计模式(六)--观察者模式
- java第一课
- JAVA中Long与Integer比较容易犯的错误
- Java swing 中线程问题(事件分发线程)
- eclipse无法连接到makertplace
- java的(PO,VO,TO,BO,DAO,POJO)包解释
- java log4j.xml配置
- 关于 Java(TM) Platform SE binary 已停止工作 的解决方法
- eclipse怎样修改包(package)的显示样式、格式 工具/原料
- 【JavaWeb】【笔记】《JavaWeb入门经典》 第15章 Struts框架
- spring下批量注册jsonrpc的JSONRPCBridge