在sping 中 用freemarker 非常简单,仅仅只需注意两个地方就可以上手开发了。
第一点:在spring配置文件 applicationContext.xml中添加 freeMarkerConfigurer bean
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.wsy.baobaotao.front.service"/>
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.126.com"/>
<property name="port" value="25"/>
<property name="username" value="xxxx@126.com"/>
<property name="password" value="xxxx"/>
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
</props>
</property>
</bean>
<bean id="freeMarkerConfigurer" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPaths" value="classpath:template/simple,template/jquery"/>
<property name="freemarkerSettings">
<props>
<prop key="template_update_delay">1800</prop><!--刷新模板的周期,单位为秒-->
<prop key="default_encoding">UTF-8</prop>
</props>
</property>
</bean>
</beans>
第二点:在service层中 利用@Autowired 关键字注入 第一点添加的 freeMarkerConfigurer ,然后用它来获取模版文件。
package com.wsy.baobaotao.front.service.impl;
import java.util.Locale;
import java.util.Map;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import com.wsy.baobaotao.front.service.EmailService;
import freemarker.template.Template;
@Service
public class EmailServiceImpl implements EmailService {
@Autowired
private JavaMailSender mailSender;
@Autowired
private FreeMarkerConfigurer freeMarkerConfigurer;
/**
* 生成html模板字符串
*
* @param root
* 存储动态数据的map
* @return
*/
private String getTemplateText(Map<String, Object> root, String templateName) {
String htmlText = "";
try {
Locale locale = new Locale("zh_CN");
// 通过指定模板名获取FreeMarker模板实例
Template tpl = freeMarkerConfigurer.getConfiguration().getTemplate(templateName, locale);
htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(tpl,root);
} catch (Exception e) {
e.printStackTrace();
}
return htmlText;
}
}