搜尋
首頁web前端html教學Velocity练习:使用vm模板生成最简单的html页面_html/css_WEB-ITnose

这几天要用到Velocity模板引擎去做一些页面,所以学习了下这个工具。我的jdk版本为 1.8.0_25

需要做的准备工作有:

1、建立一个Java工程,需要引用Velocity相关的jar包,这些jar包可从apache.org下载到最新版本。 下载地址在:http://velocity.apache.org/download.cgi 。我下载的文件是velocity-tools-2.0.zip,将这些文件导入到项目中,就可以使用Velocity进行编码了。

2、安装Eclipse上的Velocity插件Veloedit。因为googlecode被gfw墙掉了,没有条件的朋友们可以安装网上下载到的离线安装版。这里还有一个需要注意,我的Eclipse版本为 Luna Service Release 1 (4.4.1),这个版本必须要先利用Eclipse自带的update功能,下载“Elipse Tests, Examples, and Extras”。

建立一个JavaProject,取名VelocityTool,里面新建两个java文件。

其中,VelocityHelper.java包含一个Velocity模板转换工具类,代码如下:

import java.io.File;import java.io.FileWriter;import org.apache.velocity.Template;import org.apache.velocity.VelocityContext;import org.apache.velocity.app.Velocity;import org.apache.velocity.app.VelocityEngine;/** *  * @文件名称 VelocityHelper.java * @文件作者 Tsybius2014 * @创建时间 2016年5月10日 下午2:14:01 */public class VelocityHelper {    /**     *      * @param inputVmFilePath     * @param outputHtmlFilePath     * @param context     * @throws Exception     */    public static void generateHtml(String inputVmFilePath, String outputHtmlFilePath,        VelocityContext context) throws Exception {        try {            Velocity.init();            VelocityEngine engine = new VelocityEngine();            Template template = engine.getTemplate(inputVmFilePath, "gbk");            File outputFile = new File(outputHtmlFilePath);             FileWriter writer = new FileWriter(outputFile);            template.merge(context, writer);            writer.close();        } catch (Exception ex) {            throw ex;        }    }}

VelocityTool.java中有main函数,代码如下:

import java.util.HashMap;import java.util.Vector;import org.apache.velocity.VelocityContext;/** *  * @文件名称 VelocityTool.java * @文件作者 Tsybius2014 * @创建时间 2016年5月10日 上午10:03:59 */public class VelocityTool {    public static void main(String[] args) {        try {            VelocityContext context= new VelocityContext();            context.put("name", "Kim Jung-un");            context.put("gender", "Male");            context.put("email", "XXX@XXX.gov");            context.put("job", "Chairman of the WPK");            context.put("company", "Workers' Party Of Korea (WPK)");            context.put("address", "XXXXXXXXX, Pyongyang, North Korea");            context.put("portraitPath", "file:///C:/Users/Tsybius/Desktop/kju.jpg");            HashMap<String, String> hashMapContact = new HashMap<String, String>();            hashMapContact.put("Tel", "XXX-XXXXXXXX");            hashMapContact.put("Fax", "XXX-XXXXXXXX");            hashMapContact.put("Mobile", "XXX-XXXX-XXXX");            context.put("contactItems", hashMapContact);            Vector<String> vectorRemark = new Vector<String>();            vectorRemark.add("Kim Jong-un is the Chairman of the Workers' Party of Korea and supreme leader of the Democratic People's Republic of Korea (DPRK), commonly referred to as North Korea.");            vectorRemark.add("Kim is the son of Kim Jong-il (1941–2011) and the grandson of Kim Il-sung (1912–1994).");            vectorRemark.add("Kim obtained two degrees, one in Physics at Kim Il-sung University, and another as an Army officer at the Kim Il-sung Military University.");            vectorRemark.add("Kim was named the World's 46th Most Powerful Person by the Forbes list of The World's Most Powerful People in 2013");            context.put("remarks", vectorRemark);            VelocityHelper.generateHtml(                "velocity_test.vm",                 "C:\\Users\\Tsybius\\Desktop\\output.html",                 context);            System.out.println("生成完毕");        } catch (Exception ex) {            ex.printStackTrace();        }    }}

模板velocity_test.vm是一个存储着人物通讯录的模板,代码如下:

#set($docDesc="VelocityTest")#set($docAuthor="Tsybius2014")#set($docDateTime="2016-05-10 14:29:04")#set($docRemark="none")<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml">  <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />  <style type="text/css">  </style>  <head>    <title>$!{name}</title>  </head>  <body>    <table width="100%">      <tr>        <!-- Title -->        <td align="center"><b>Address Book - $!{name}</b></td>      </tr>      <tr>        <!-- BaseInfo -->        <td>          <table width="100%" height="100%">            <tr>              <td width="10%">Name:</td>              <td width="30%">$!{name}</td>              <td width="10%">Gender:</td>              <td width="30%">$!{gender}</td>              <td width="20%" rowspan="4">                <img  src="/static/imghwm/default1.png"  data-src="$!{portraitPath}"  class="lazy"    style="max-width:90%"  style="max-width:90%"/ alt="Velocity练习:使用vm模板生成最简单的html页面_html/css_WEB-ITnose" >              </td>            </tr>            <tr>              <td width="10%">E-mail:</td>              <td width="30%">$!{email}</td>              <td width="10%">Job:</td>              <td width="30%">$!{job}</td>            </tr>            <tr>              <td width="10%">Company:</td>              <td width="70%" colspan="3">$!{company}</td>            </tr>            <tr>              <td width="10%">Address:</td>              <td width="70%" colspan="3">$!{address}</td>            </tr>          </table>        </td>      </tr>      <tr>        <!-- Contact -->        <td>          <table width="100%" height="100%" >            <tr>              <td width="10%" align="left" valign="top">                Contact:              </td>              <td>                <table width="100%" height="100%" >                  <tr>                    <th></th>                    <th align="left">Contact Type</th>                    <th align="left">Contact Code</th>                    <th></th>                  </tr>                  #foreach($contactItem in $contactItems.entrySet())                    <tr>                      <td align="left" width="5%">$velocityCount</td>                      <td align="left" width="20%">$contactItem.key</td>                      <td align="left" width="30%">$contactItem.value</td>                      <td></td>                    </tr>                  #end                 </table>              </td>            </tr>          </table>        </td>      </tr>      <tr>        <!-- Remarks-->        <td>          <table width="100%" height="100%" >            <tr>              <td width="10%" align="left" valign="top">                Remark:              </td>              <td>                <table width="100%" height="100%" >                  #foreach($remark in $remarks)                    <tr>                      <td>[$velocityCount] $remark</td>                    </tr>                  #end                 </table>              </td>            </tr>          </table>        </td>      </tr>    </table>  </body></html>

以JavaApplication的方式运行本工程后,生成的HTML页面output.html如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml">  <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />  <style type="text/css">  </style>  <head>    <title>Kim Jung-un</title>  </head>  <body>    <table width="100%">      <tr>        <!-- Title -->        <td align="center"><b>Address Book - Kim Jung-un</b></td>      </tr>      <tr>        <!-- BaseInfo -->        <td>          <table width="100%" height="100%">            <tr>              <td width="10%">Name:</td>              <td width="30%">Kim Jung-un</td>              <td width="10%">Gender:</td>              <td width="30%">Male</td>              <td width="20%" rowspan="4">                <img  src="/static/imghwm/default1.png"  data-src="file:///C:/Users/Tsybius/Desktop/kju.jpg"  class="lazy"    style="max-width:90%"  style="max-width:90%"/ alt="Velocity练习:使用vm模板生成最简单的html页面_html/css_WEB-ITnose" >              </td>            </tr>            <tr>              <td width="10%">E-mail:</td>              <td width="30%">kim001@northkorea.gov</td>              <td width="10%">Job:</td>              <td width="30%">Chairman of the WPK</td>            </tr>            <tr>              <td width="10%">Company:</td>              <td width="70%" colspan="3">Workers' Party Of Korea (WPK)</td>            </tr>            <tr>              <td width="10%">Address:</td>              <td width="70%" colspan="3">The Dark Side Laboratory, Pyongyang, North Korea</td>            </tr>          </table>        </td>      </tr>      <tr>        <!-- Contact -->        <td>          <table width="100%" height="100%" >            <tr>              <td width="10%" align="left" valign="top">                Contact:              </td>              <td>                <table width="100%" height="100%" >                  <tr>                    <th></th>                    <th align="left">Contact Type</th>                    <th align="left">Contact Code</th>                    <th></th>                  </tr>                    <tr>                      <td align="left" width="5%">1</td>                      <td align="left" width="20%">Tel</td>                      <td align="left" width="30%">XXX-XXXXXXXX</td>                      <td></td>                    </tr>                    <tr>                      <td align="left" width="5%">2</td>                      <td align="left" width="20%">Fax</td>                      <td align="left" width="30%">XXX-XXXXXXXX</td>                      <td></td>                    </tr>                    <tr>                      <td align="left" width="5%">3</td>                      <td align="left" width="20%">Mobile</td>                      <td align="left" width="30%">XXX-XXXX-XXXX</td>                      <td></td>                    </tr>                  </table>              </td>            </tr>          </table>        </td>      </tr>      <tr>        <!-- Remarks-->        <td>          <table width="100%" height="100%" >            <tr>              <td width="10%" align="left" valign="top">                Remark:              </td>              <td>                <table width="100%" height="100%" >                  <tr>                    <td>[1] Kim Jong-un is the Chairman of the Workers' Party of Korea and supreme leader of the Democratic People's Republic of Korea (DPRK), commonly referred to as North Korea.</td>                  </tr>                  <tr>                    <td>[2] Kim is the son of Kim Jong-il (1941–2011) and the grandson of Kim Il-sung (1912–1994).</td>                  </tr>                  <tr>                    <td>[3] Kim obtained two degrees, one in Physics at Kim Il-sung University, and another as an Army officer at the Kim Il-sung Military University.</td>                  </tr>                  <tr>                    <td>[4] Kim was named the World's 46th Most Powerful Person by the Forbes list of The World's Most Powerful People in 2013</td>                  </tr>                </table>              </td>            </tr>          </table>        </td>      </tr>    </table>  </body></html>

使用 Firefox 46.0.1 打开此页面后效果图如下:

(部分内容摘自对应人物的维基百科页面)

END

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
HTML:結構,CSS:樣式,JavaScript:行為HTML:結構,CSS:樣式,JavaScript:行為Apr 18, 2025 am 12:09 AM

HTML、CSS和JavaScript在Web開發中的作用分別是:1.HTML定義網頁結構,2.CSS控製網頁樣式,3.JavaScript添加動態行為。它們共同構建了現代網站的框架、美觀和交互性。

HTML的未來:網絡設計的發展和趨勢HTML的未來:網絡設計的發展和趨勢Apr 17, 2025 am 12:12 AM

HTML的未來充滿了無限可能。 1)新功能和標準將包括更多的語義化標籤和WebComponents的普及。 2)網頁設計趨勢將繼續向響應式和無障礙設計發展。 3)性能優化將通過響應式圖片加載和延遲加載技術提升用戶體驗。

HTML與CSS vs. JavaScript:比較概述HTML與CSS vs. JavaScript:比較概述Apr 16, 2025 am 12:04 AM

HTML、CSS和JavaScript在網頁開發中的角色分別是:HTML負責內容結構,CSS負責樣式,JavaScript負責動態行為。 1.HTML通過標籤定義網頁結構和內容,確保語義化。 2.CSS通過選擇器和屬性控製網頁樣式,使其美觀易讀。 3.JavaScript通過腳本控製網頁行為,實現動態和交互功能。

HTML:是編程語言還是其他?HTML:是編程語言還是其他?Apr 15, 2025 am 12:13 AM

HTMLISNOTAPROGRAMMENGUAGE; ITISAMARKUMARKUPLAGUAGE.1)htmlStructures andFormatSwebContentusingtags.2)itworkswithcsssforstylingandjavascript for Interactivity,增強WebevebDevelopment。

HTML:建立網頁的結構HTML:建立網頁的結構Apr 14, 2025 am 12:14 AM

HTML是構建網頁結構的基石。 1.HTML定義內容結構和語義,使用、、等標籤。 2.提供語義化標記,如、、等,提升SEO效果。 3.通過標籤實現用戶交互,需注意表單驗證。 4.使用、等高級元素結合JavaScript實現動態效果。 5.常見錯誤包括標籤未閉合和屬性值未加引號,需使用驗證工具。 6.優化策略包括減少HTTP請求、壓縮HTML、使用語義化標籤等。

從文本到網站:HTML的力量從文本到網站:HTML的力量Apr 13, 2025 am 12:07 AM

HTML是一種用於構建網頁的語言,通過標籤和屬性定義網頁結構和內容。 1)HTML通過標籤組織文檔結構,如、。 2)瀏覽器解析HTML構建DOM並渲染網頁。 3)HTML5的新特性如、、增強了多媒體功能。 4)常見錯誤包括標籤未閉合和屬性值未加引號。 5)優化建議包括使用語義化標籤和減少文件大小。

了解HTML,CSS和JavaScript:初學者指南了解HTML,CSS和JavaScript:初學者指南Apr 12, 2025 am 12:02 AM

WebDevelovermentReliesonHtml,CSS和JavaScript:1)HTMLStructuresContent,2)CSSStyleSIT和3)JavaScriptAddSstractivity,形成thebasisofmodernWebemodernWebExexperiences。

HTML的角色:構建Web內容HTML的角色:構建Web內容Apr 11, 2025 am 12:12 AM

HTML的作用是通過標籤和屬性定義網頁的結構和內容。 1.HTML通過到、等標籤組織內容,使其易於閱讀和理解。 2.使用語義化標籤如、等增強可訪問性和SEO。 3.優化HTML代碼可以提高網頁加載速度和用戶體驗。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 個月前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
1 個月前By尊渡假赌尊渡假赌尊渡假赌
威爾R.E.P.O.有交叉遊戲嗎?
1 個月前By尊渡假赌尊渡假赌尊渡假赌

熱工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境