Home Web Front-end HTML Tutorial Velocity练习:使用vm模板生成最简单的html页面_html/css_WEB-ITnose

Velocity练习:使用vm模板生成最简单的html页面_html/css_WEB-ITnose

Jun 21, 2016 am 08:48 AM

这几天要用到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;        }    }}
Copy after login

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();        }    }}
Copy after login

模板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/imghw/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>
Copy after login

以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/imghw/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>
Copy after login

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

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

END

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the purpose of the <progress> element? What is the purpose of the <progress> element? Mar 21, 2025 pm 12:34 PM

The article discusses the HTML &lt;progress&gt; element, its purpose, styling, and differences from the &lt;meter&gt; element. The main focus is on using &lt;progress&gt; for task completion and &lt;meter&gt; for stati

Is HTML easy to learn for beginners? Is HTML easy to learn for beginners? Apr 07, 2025 am 12:11 AM

HTML is suitable for beginners because it is simple and easy to learn and can quickly see results. 1) The learning curve of HTML is smooth and easy to get started. 2) Just master the basic tags to start creating web pages. 3) High flexibility and can be used in combination with CSS and JavaScript. 4) Rich learning resources and modern tools support the learning process.

What is the purpose of the <datalist> element? What is the purpose of the <datalist> element? Mar 21, 2025 pm 12:33 PM

The article discusses the HTML &lt;datalist&gt; element, which enhances forms by providing autocomplete suggestions, improving user experience and reducing errors.Character count: 159

What is the viewport meta tag? Why is it important for responsive design? What is the viewport meta tag? Why is it important for responsive design? Mar 20, 2025 pm 05:56 PM

The article discusses the viewport meta tag, essential for responsive web design on mobile devices. It explains how proper use ensures optimal content scaling and user interaction, while misuse can lead to design and accessibility issues.

What is the purpose of the <iframe> tag? What are the security considerations when using it? What is the purpose of the <iframe> tag? What are the security considerations when using it? Mar 20, 2025 pm 06:05 PM

The article discusses the &lt;iframe&gt; tag's purpose in embedding external content into webpages, its common uses, security risks, and alternatives like object tags and APIs.

The Roles of HTML, CSS, and JavaScript: Core Responsibilities The Roles of HTML, CSS, and JavaScript: Core Responsibilities Apr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

What is the purpose of the <meter> element? What is the purpose of the <meter> element? Mar 21, 2025 pm 12:35 PM

The article discusses the HTML &lt;meter&gt; element, used for displaying scalar or fractional values within a range, and its common applications in web development. It differentiates &lt;meter&gt; from &lt;progress&gt; and ex

Understanding HTML, CSS, and JavaScript: A Beginner's Guide Understanding HTML, CSS, and JavaScript: A Beginner's Guide Apr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

See all articles