Java筆記-SpringMVC中利用Velocity渲染HTML發(fā)送郵件

Velocity:基于Java的模板引擎,可以用Java代碼渲染的簡(jiǎn)單而又強(qiáng)大的模板語(yǔ)言。開(kāi)發(fā)Web時(shí),可以將Web頁(yè)面和Java代碼分離,類(lèi)似JSP和PHP。詳細(xì)介紹:參見(jiàn)官網(wǎng):Apache Velocity Project

本篇文章以發(fā)送郵件為例子,介紹一下Velocity簡(jiǎn)單的實(shí)際用法

步驟:pom.xml引入包 => xml文件添加配置 => 配置視圖 => Java代碼

步驟一:maven添加依賴(lài)包

pom.xml文件里引入下面的配置代碼

<dependency>
  <groupId>org.apache.velocity</groupId>
  <artifactId>velocity</artifactId>
  <version>1.7</version>
</dependency>
<dependency>
  <groupId>org.apache.velocity</groupId>
  <artifactId>velocity-tools</artifactId>
  <version>2.0</version>
</dependency>

步驟二:xml里面添加Velocity配置

在配置文件applicationContext.xml中加入配置,這里可以有兩種方式

  • 配置文件方式,即Velocity的屬性通過(guò)配置文件方式來(lái)設(shè)置
<bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
        <property name="resourceLoaderPath" value="/WEB-INF/velocity/"/><!-- 模板存放的路徑 -->
        <property name="configLocation" value="classpath:velocity.properties"/><!-- Velocity的配置文件 -->
</bean>

resources下面新建velocity.properties文件

input.encoding=UTF-8  
output.encoding=UTF-8  
contentType=ext/html;charset=UTF-8
directive.foreach.counter.name=loopCounter  
directive.foreach.counter.initial.value=0  
  • 直接設(shè)置屬性方式,即Velocity的屬性通過(guò)<prop>標(biāo)簽直接設(shè)置,也就是將第一種方式合為一步,省去單獨(dú)設(shè)置配置文件的麻煩
<bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
        <property name="resourceLoaderPath" value="/WEB-INF/velocity/"/><!-- 模板存放的路徑 -->
        <property name="velocityProperties">    
        <props>    
            <prop key="directive.foreach.counter.name">loopCounter</prop>    
            <prop key="directive.foreach.counter.initial.value">0</prop>   
            <prop key="contentType">text/html;charset=UTF-8</prop> 
            <prop key="input.encoding">UTF-8</prop> 
            <prop key="output.encoding">UTF-8</prop>
        </props>    
    </property>  
</bean>

步驟三:配置視圖

在WEB-INF路徑下新建velocity文件夾,文件夾里新建后綴為vm的模板文件,這里說(shuō)的文件路徑對(duì)應(yīng)步驟二中的模板存放路徑

下面是一個(gè)簡(jiǎn)單的郵件模板,模板內(nèi)容是一個(gè)表格,也就是發(fā)送一個(gè)內(nèi)容為一個(gè)表格的郵件。其中,表格的body是通過(guò)二層for循環(huán)動(dòng)態(tài)設(shè)定的數(shù)據(jù),具體的velocity語(yǔ)法,自行百度

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        table {
            border-collapse: collapse;
            width: 100%;
        }

        td {
            padding: 6px 8px;
            text-align: center;
            border: solid #000 1px;
        }

        th {
            padding: 6px 8px;
            background: #e2e2e2;
            border: solid #000 1px;
        }
    </style>
</head>
<body>
<h3>數(shù)據(jù)日期:${date}</h3>
<table>
    <thead>
    <tr>
        <th>數(shù)據(jù)A</th>
        <th>數(shù)據(jù)B</th>
        <th>數(shù)據(jù)C</th>
        <th>數(shù)據(jù)D</th>
    </tr>
    </thead>
    <tbody>
        #foreach($rowData in $data)
        <tr>
            #foreach($columnData in $rowData)
                <td>$columnData</td>
            #end
        </tr>
        #end
    </tbody>
</table>
</body>
</html>

步驟四:Java代碼初始化數(shù)據(jù)

這里不介紹具體的發(fā)送郵件的Api,類(lèi)似JavaMail的庫(kù)網(wǎng)上很多。步驟三中寫(xiě)好了模板文件,現(xiàn)在需要利用Java代碼將數(shù)據(jù)填充到模板文件里面,這里用Map數(shù)據(jù)結(jié)構(gòu)存放需要渲染的原始數(shù)據(jù)

private void sendMail() throws JobExecutionException {
        String[] to = { "收件人" };
        String subject = "主題";
        String[] cc = {};
        Map<String, Object> model = new HashMap<>();
        model.put("date", "2017-09-17");
        List<List> data = new ArrayList<>();
        List row1 = new ArrayList();
        list.add("A data");
        list.add("B data");
        list.add("C data");
        list.add("D data");
        List row2 = new ArrayList();
        list.add("A data");
        list.add("B data");
        list.add("C data");
        list.add("D data");
        data.add(row1);
        data.add(row2);
        model.put("data", list);
        String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "DataValidator.vm", "UTF-8", model);
        try {
            EmailUtil.send(to, subject, body, cc);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

注意,velocityEngine需要注入一下這個(gè)實(shí)例,例如在serviceImpl中通過(guò)@Autowired注入

@Autowired
private VelocityEngine velocityEngine;
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,285評(píng)論 6 342
  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,694評(píng)論 19 139
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語(yǔ)法,類(lèi)相關(guān)的語(yǔ)法,內(nèi)部類(lèi)的語(yǔ)法,繼承相關(guān)的語(yǔ)法,異常的語(yǔ)法,線(xiàn)程的語(yǔ)...
    子非魚(yú)_t_閱讀 34,835評(píng)論 18 399
  • 我所渴望的美,是永恒與生命,誰(shuí)知它們竟水火不容;永恒的美,奇光異彩,卻無(wú)感無(wú)情;生命的美,千變?nèi)f化,卻終為灰燼?!?..
    福爾摩雞閱讀 2,065評(píng)論 2 4
  • 留人容易,留人才難,優(yōu)秀員工的離開(kāi)并非是突然,因?yàn)楣芾碚呋蛘吖局贫鹊膯?wèn)題,優(yōu)秀員工往往最先離職,因?yàn)樗麄儠?huì)有更多...
    4abd7e01a4e2閱讀 739評(píng)論 0 0

友情鏈接更多精彩內(nèi)容