最近几天项目提出发送邮件的功能,该接口暂且不提。
目前的需求:生成<body></body>体,传给发送邮件接口。
send的<body></body>体上司要我用velocity或freemarker或thymeleaf去做,方便后期维护。
thymeleaf高度依赖spring,网上其他的教程很少,尝试了半天之后我选择了放弃。
我只是需要在代码中读取静态html,将数据组装进入后return一个String类型的body体,没必要那么复杂。
freemarker与velocity好很多,都是基于Java的,这点比thymeleaf强,看起来都能够实现我的需求。
我先尝试了velocity,很简单,直接完美实现,简单粗暴。
freemarker我也简单尝试了下,没有实现,但比起thymeleaf要好不少,java的代码很多。
总结:如果只是实现如下的需求,直接选择velocity即可,简单粗暴,在静态资源下放入模板即可。
eg:
//初始化VelocityEngine
public VelocityEngine VelocityEngineInit(){
//实体,设置默认项目路径
VelocityEngine ModelVelocityEngine = new VelocityEngine();
ModelVelocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
ModelVelocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
//设置velocity的编码
ModelVelocityEngine.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
//初始化
ModelVelocityEngine.init();
return ModelVelocityEngine;
}
//组装标准模板A
public String commonModel(String content,StringBuffer fileDate,String shares){
//初始化VelocityEngine
VelocityEngine aModelVelocityE = VelocityEngineInit();
//获取静态模板
Template at = aModelVelocityE.getTemplate("velocityModel/标准模板-A.vm");
//组装参数
VelocityContext aCtx = new VelocityContext();
aCtx.put("content", content);
aCtx.put("filedate", fileDate);
aCtx.put("shares", shares);
StringWriter aSw = new StringWriter();
at.merge(aCtx, aSw);
return aSw.toString();
}
//组装标准模板B
public String commonModel(String content,StringBuffer fileDate){
//初始化VelocityEngine
VelocityEngine bModelVelocityE = VelocityEngineInit();
//获取静态模板
Template bt = bModelVelocityE.getTemplate("velocityModel/标准模板-B.vm");
//组装参数
VelocityContext bCtx = new VelocityContext();
bCtx.put("content", content);
bCtx.put("filedate", fileDate);
StringWriter bSw = new StringWriter();
bt.merge(bCtx, bSw);
return bSw.toString();
}
public static void main(String []args){
MailModel mail=new MailModel();
System.out.println(mail.commonModel("123",new StringBuffer("12321"),"213"));
}
<body style="width: auto;height: auto;">
<div style="width: auto;height: auto;padding-top: 5%;">
<div style="width: 400px; height: auto;background-color: #FAFAFA;margin:0 auto;">
<div style="width: 360px;height: auto;margin:0 auto;padding-top:5%;">
<div>
</div>
<div style="border-bottom:1px solid #999999;width: 340px;">
<p ><strong style="font-size: 16px;;">来自fileknox的邮件: </strong></p>
</div>
<div>
<div style="margin-top: 5%">
<div style="font-size: 12px;float:left;color: #666666;">邮件内容: </div>
<div style="font-size: 12px;">
$content
</div>
</div>
<div style="margin-top: 5%">
<div style="font-size: 12px;float:left;color: #666666;">分享文件: </div>
<div style="font-size: 12px;">
<p>
$filedate
</p>
</div>
</div>
<div style="margin-top: 5%;height: 50px;">
<div style="font-size: 12px;float:left;color: #666666;">提取密码: </div>
<div>
<p style="color: #40A3FF;font-size: 12px;">
$shares
</p>
</div>
</div>
</div>
</div>
</div>
</div>
</body>