工程中使用了邮件和短信模板,,
内容使用的html代码, vm文件。
可以使用Spring 的解析工具解析,替换其中的动态数据 。
FreeMarker解析:
@Autowired
private FreeMarkerConfigurer freeMarkerConfigurer;
public String getFtlText(Map data,String ftl){
String htmlText=null;
Template tpl = null;
try {
tpl = freeMarkerConfigurer.getConfiguration().getTemplate(ftl);//加载资源文件
htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(tpl, data);//加入map到模板中 对应${content}
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}
return htmlText;
}
注: 其中的 freeMarkerConfigurer 可以在Spring中配置如下:
<bean id="freeMarkerConfigurer" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"> <property name="templateLoaderPaths" value="classpath:template/sms" /> <property name="freemarkerSettings"> <props> <prop key="template_update_delay">1800</prop><!-- 模板更新延时 --> <prop key="default_encoding">UTF-8</prop> <prop key="locale">zh_CN</prop> </props> </property> </bean>
VM 文件 :
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>处理中</title>
</head>
<body>
<div style="background:#F6F5F6;padding:5px;width:630px;font-size:12px;color:#2D2D2D;font-family:tahoma">
<table style="background:#fff;width:630px;border-spacing:0;border-collapse:collapse;font-size:12px;color:#2D2D2D;font-family:tahoma">
<tr>
<td style="background:#FEEAC2;height:32px;line-height:32px;padding:0;">
<table style="width:100%">
<tr>
.................此处几乎不使用图片,且样式全部套在标签内.................
....................................
..................................
<tr>
<td style="padding-bottom:10px;">很高兴通知您以下订单已经成功提交: </td>
</tr>
<tr>
<td style="padding:5px 0;font-weight:bold;">订单详情</td>
</tr>
<tr>
<td style="padding:5px 0;">城市: [${hotelOrder.cityName}]</td>
</tr>
<tr>
<td style="padding:5px 0;">酒店名称: ${hotelOrder.hotelName}</td>
</tr>
<tr>
<td style="padding:5px 0;">入住日期:${hotelOrder.strEnterDate}</td>
</tr>
<tr>
<td style="padding:5px 0;">入住天数: ${hotelOrder.leaveDay} </td>
</tr>
.................................................
.................................................
.................................................
解析的方法:
data.put("module", 2);
data.put("orderNo", orderNo);
data.put("email", email);
data.put("hotelOrder", hotelOrder);
getContent(data,templateId + ".vm");
public String getContent(Map dataMap,String vmString) {
String body = getBody(dataMap, vmString);
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
try {
response.getWriter().append(body);
response.flushBuffer();
} catch (IOException e) {
e.printStackTrace();
}
return NONE;
}
public String getBody(Map<String, Object> dataMap, String tpl) {
String body = VelocityEngineUtils.mergeTemplateIntoString(
velocityEngine, tpl, dataMap);
return body;
}