最近幾天項目提出發送郵件的功能,該接口暫且不提。
目前的需求:生成<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>