代码拉取完成,页面将自动刷新
<!DOCTYPE HTML>
<html >
<head>
<meta charset="UTF-8">
<title>Hexo</title>
<meta name="viewport" content="width=device-width, initial-scale=1,user-scalable=no">
<meta name="author" content="闫笑南">
<meta property="og:type" content="website">
<meta property="og:title" content="Hexo">
<meta property="og:url" content="http://git.oschina.net/index.html">
<meta property="og:site_name" content="Hexo">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Hexo">
<link rel="alternative" href="/atom.xml" title="Hexo" type="application/atom+xml">
<link rel="icon" href="/note/img/favicon.ico">
<link rel="apple-touch-icon" href="/note/img/jacman.jpg">
<link rel="apple-touch-icon-precomposed" href="/note/img/jacman.jpg">
<link rel="stylesheet" href="/note/css/style.css">
</head>
<body>
<header>
<div>
<div id="imglogo">
<a href="/note/"><img src="/note/img/logo.png" alt="Hexo" title="Hexo"/></a>
</div>
<div id="textlogo">
<h1 class="site-name"><a href="/note/" title="Hexo">Hexo</a></h1>
<h2 class="blog-motto"></h2>
</div>
<div class="navbar"><a class="navbutton navmobile" href="#" title="Menu">
</a></div>
<nav class="animated">
<ul>
<ul>
<li><a href="/note/">Home</a></li>
<li><a href="/note/archives">Archives</a></li>
<li><a href="/note/about">About</a></li>
<li>
<form class="search" action="//google.com/search" method="get" accept-charset="utf-8">
<label>Search</label>
<input type="search" id="search" name="q" autocomplete="off" maxlength="20" placeholder="Search" />
<input type="hidden" name="q" value="site:git.oschina.net">
</form>
</li>
</ul>
</nav>
</div>
</header>
<div id="container">
<div id="main">
<article class="post-expand post" itemprop="articleBody">
<header class="article-info clearfix">
<h1 itemprop="name">
<a href="/note/2017/04/26/使用volicity快速生成代码/" title="" itemprop="url"></a>
</h1>
<p class="article-author">By
<a href="/note/about" title="闫笑南" target="_blank" itemprop="author">闫笑南</a>
<p class="article-time">
<time datetime="2017-04-26T13:24:27.980Z" itemprop="datePublished"> Published 2017-04-26</time>
</p>
</header>
<div class="article-content">
<p><strong>Velocity 模板引擎介绍</strong></p>
<p>在现今的软件开发过程中,软件开发人员将更多的精力投入在了重复的相似劳动中。特别是在如今特别流行的 MVC 架构模式中,软件各个层次的功能更加独立,同时代码的相似度也更加高。所以我们需要寻找一种来减少软件开发人员重复劳动的方法,让程序员将更多的精力放在业务逻辑以及其他更加具有创造力的工作上。Velocity 这个模板引擎就可以在一定程度上解决这个问题。<br>Velocity 是一个基于 Java 的模板引擎框架,提供的模板语言可以使用在 Java 中定义的对象和变量上。Velocity 是 Apache 基金会的项目,开发的目标是分离 MVC 模式中的持久化层和业务层。但是在实际应用过程中,Velocity 不仅仅被用在了 MVC 的架构中,还可以被用在以下一些场景中。<br>1.Web 应用:开发者在不使用 JSP 的情况下,可以用 Velocity 让 HTML 具有动态内容的特性。</p>
<ol>
<li>源代码生成:Velocity 可以被用来生成 Java 代码、SQL 或者 PostScript。有很多开源和商业开发的软件是使用 Velocity 来开发的。</li>
<li>自动 Email:很多软件的用户注册、密码提醒或者报表都是使用 Velocity 来自动生成的。使用 Velocity 可以在文本文件里面生成邮件内容,而不是在 Java 代码中拼接字符串。</li>
<li>转换 xml:Velocity 提供一个叫 Anakia 的 ant 任务,可以读取 XML 文件并让它能够被 Velocity 模板读取。一个比较普遍的应用是将 xdoc 文档转换成带样式的 HTML 文件。</li>
</ol>
<p><em>Hello Velocity</em></p>
<p>和学习所有新的语言或者框架的顺序一样,我们从 Hello Velocity 开始学习。首先在 Velocity 的官网上下载最新的发布包,之后使用 Eclipse 建立普通的 Java 项目。引入解压包中的 velocity-1.7.jar 和 lib 文件夹下面的 jar 包。这样我们就可以在项目中使用 Velocity 了。<br>在做完上面的准备工作之后,就可以新建一个叫 HelloVelocity 的类,代码如下:<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//清单 1.</span></div><div class="line">HelloVelocity.java</div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HelloVelocity</span> </span>{</div><div class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>{</div><div class="line"> VelocityEngine ve = <span class="keyword">new</span> VelocityEngine();</div><div class="line"> ve.setProperty(RuntimeConstants.RESOURCE_LOADER, <span class="string">"classpath"</span>);</div><div class="line"> ve.setProperty(<span class="string">"classpath.resource.loader.class"</span>, ClasspathResourceLoader.class.getName());</div><div class="line"></div><div class="line"> ve.init();</div><div class="line"></div><div class="line"> Template t = ve.getTemplate(<span class="string">"hellovelocity.vm"</span>);</div><div class="line"> VelocityContext ctx = <span class="keyword">new</span> VelocityContext();</div><div class="line"></div><div class="line"> ctx.put(<span class="string">"name"</span>, <span class="string">"velocity"</span>);</div><div class="line"> ctx.put(<span class="string">"date"</span>, (<span class="keyword">new</span> Date()).toString());</div><div class="line"></div><div class="line"> List temp = <span class="keyword">new</span> ArrayList();</div><div class="line"> temp.add(<span class="string">"1"</span>);</div><div class="line"> temp.add(<span class="string">"2"</span>);</div><div class="line"> ctx.put(<span class="string">"list"</span>, temp);</div><div class="line"></div><div class="line"> StringWriter sw = <span class="keyword">new</span> StringWriter();</div><div class="line"></div><div class="line"> t.merge(ctx, sw);</div><div class="line"></div><div class="line"> System.out.println(sw.toString());</div><div class="line"> }</div><div class="line">}</div></pre></td></tr></table></figure></p>
<p>在 HelloVelocity 的代码中,首先 new 了一个 VelocityEngine 类,这个类设置了 Velocity 使用的一些配置,在初始化引擎之后就可以读取 hellovelocity.vm 这个模板生成的 Template 这个类。之后的 VelocityContext 类是配置 Velocity 模板读取的内容。这个 context 可以存入任意类型的对象或者变量,让 template 来读取。这个操作就像是在使用 JSP 开发时,往 request 里面放入 key-value,让 JSP 读取一样。<br>接下来就是写 hellovelocity.vm 文件了,这个文件实际定义了 Velocity 的输出内容和格式。hellovelocity.vm 的内容如下:</p>
<p>清单 2. Hellovelocity.vm<br><figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">#set( $iAmVariable = "good!" )</div><div class="line">Welcome $name to velocity.com</div><div class="line">today is $date.</div><div class="line">#foreach ($i in $list)</div><div class="line">$i</div><div class="line">#end</div><div class="line">$iAmVariable</div></pre></td></tr></table></figure></p>
<p>输出结果如下:<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">Welcome velocity to velocity.com</div><div class="line">today is Sun Mar <span class="number">23</span> <span class="number">19</span>:<span class="number">19</span>:<span class="number">04</span> CST <span class="number">2014</span>.</div><div class="line"><span class="number">1</span></div><div class="line"><span class="number">2</span></div><div class="line">good!</div></pre></td></tr></table></figure></p>
<p>在输出结果中我们可以看到,$name、$date 都被替换成了在 HelloVelocity.java 里面定义的变量,在 foreach 语句里面遍历了 list 的每一个元素,并打印出来。而$iAmVariable 则是在页面中使用 #set 定义的变量。<br>回页首<br>基本模板语言语法使用<br>在 hellovelocity.vm 里面可以看到很多以 # 和$符开头的内容,这些都是 Velocity 的语法。在 Velocity 中所有的关键字都是以 # 开头的,而所有的变量则是以$开头。Velocity 的语法类似于 JSP 中的 JSTL,甚至可以定义类似于函数的宏,下面来看看具体的语法规则。<br>一、变量<br>和我们所熟知的其他编程语言一样,Velocity 也可以在模板文件中有变量的概念。</p>
<ol>
<li>变量定义<br>#set($name =“velocity”)<br>等号后面的字符串 Velocity 引擎将重新解析,例如出现以$开始的字符串时,将做变量的替换。<br>#set($hello =“hello $name”)<br>上面的这个等式将会给$hello 赋值为“hello velocity”</li>
<li>变量的使用<br>在模板文件中使用$name 或者${name} 来使用定义的变量。推荐使用${name} 这种格式,因为在模板中同时可能定义了类似$name 和$names 的两个变量,如果不选用大括号的话,引擎就没有办法正确识别$names 这个变量。<br>对于一个复杂对象类型的变量,例如$person,可以使用${person.name} 来访问 person 的 name 属性。值得注意的是,这里的${person.name} 并不是直接访问 person 的 name 属性,而是访问 person 的 getName() 方法,所以${person.name} 和${person.getName()} 是一样的。</li>
<li>变量赋值<br>在第一小点中,定义了一个变量,同时给这个变量赋了值。对于 Velocity 来说,变量是弱数据类型的,可以在赋了一个 String 给变量之后再赋一个数字或者数组给它。可以将以下六种数据类型赋给一个 Velocity 变量:变量引用, 字面字符串, 属性引用, 方法引用, 字面数字, 数组列表。<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">#set($foo = $bar)</div><div class="line">#set($foo =“hello”)</div><div class="line">#set($foo.name = $bar.name)</div><div class="line">#set($foo.name = $bar.getName($arg))</div><div class="line">#set($foo = 123)</div><div class="line">#set($foo = [“foo”,$bar])</div></pre></td></tr></table></figure>
</li>
</ol>
<p>二、循环<br>在 Velocity 中循环语句的语法结构如下:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">#foreach($element in $list)</div><div class="line"> This is $element</div><div class="line"> $velocityCount</div><div class="line">#end</div></pre></td></tr></table></figure></p>
<p>Velocity 引擎会将 list 中的值循环赋给 element 变量,同时会创建一个$velocityCount 的变量作为计数,从 1 开始,每次循环都会加 1.<br>三、条件语句<br>条件语句的语法如下<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">#if(condition)</div><div class="line">...</div><div class="line">#elseif(condition)</div><div class="line">…</div><div class="line">#else</div><div class="line">…</div><div class="line">#end</div></pre></td></tr></table></figure></p>
<p>四、关系操作符<br>Velocity 引擎提供了 AND、OR 和 NOT 操作符,分别对应&&、||和! 例如:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">#if($foo && $bar)</div><div class="line">#end</div></pre></td></tr></table></figure></p>
<p>五、宏<br>Velocity 中的宏可以理解为函数定义。定义的语法如下:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">#macro(macroName arg1 arg2 …)</div><div class="line">...</div><div class="line">#end</div></pre></td></tr></table></figure></p>
<p>调用这个宏的语法是:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">#macroName(arg1 arg2 …)</div><div class="line">这里的参数之间使用空格隔开,下面是定义和使用 Velocity 宏的例子:</div><div class="line">#macro(sayHello $name)</div><div class="line">hello $name</div><div class="line">#end</div><div class="line">#sayHello(“velocity”)</div><div class="line">输出的结果为 hello velocity</div></pre></td></tr></table></figure></p>
<p>六、#parse 和 #include</p>
<p>#parse 和 #include 指令的功能都是在外部引用文件,而两者的区别是,#parse 会将引用的内容当成类似于源码文件,会将内容在引入的地方进行解析,#include 是将引入文件当成资源文件,会将引入内容原封不动地以文本输出。分别看以下例子:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">foo.vm 文件:</div><div class="line">#set($name =“velocity”)</div><div class="line">parse.vm:</div><div class="line">#parse(“foo.vm”)</div><div class="line">输出结果为:velocity</div><div class="line">include.vm:</div><div class="line">#include(“foo.vm”)</div><div class="line">输出结果为:#set($name =“velocity”)</div></pre></td></tr></table></figure></p>
<p>以上内容包含了部分 Velocity 的语法,详细的语法内容可以参考 Velocity 的官方文档。</p>
<p>自动生成代码的例子<br>在上个例子中我们可以生成任意的字符串并且打印出来,那为什么我们不能生成一些按照既定格式定义的代码并且写入文件呢。<br>在这里我们以一个实际的 demo 来完成这部分内容。相关内容的源码可以参照附件。这个 demo 的功能是要实现一个学生和老师的管理,实际上都是单张表的维护。我们希望能够只定义 model 层,来生成 MVC 的所有代码。在这个 demo 中,只自动生成 action 和 JSP 的内容,因为现在有很多工具都可以帮助我们自动生成这两个包的代码。<br>首先在 eclipse 中建立一个 Java web 工程,在例子中为了方便管理 jar 包,使用的是 maven 来建立和管理工程。建立好的工程目录结构如下图所示:<br>图 1. 项目目录结构<br>项目目录结构<br>Java Resource 中放的是 Java 源码以及资源文件,Deployed Resources 中放的是 web 相关的文件。在 Java 文件中使用了类似 Spring 的 @Component 和 @Autowired 的注解来实现 IoC,使用 @Action 这样的注解实现 MVC,而在 JSP 中则使用了 JSTL 来输出页面。在上图所示的目录中,annotation、filter、framework 和 util 这四个 package 是作为这个项目框架的,跟业务没有关系,类似于 spring 和 struts 的功能。<br>在实际的项目中我们当然希望能够一开始就编写一个通用的模板文件,然后一下子生成所有的代码,但是很多时候这样做是不可能的,或者说比较困难。为了解决这个问题,我们可以在编写 Velocity 模板文件之前先按照原本的流程编写代码,暂时先忘掉 Velocity。编写的代码应该能够在一个功能上完整的调通涉及 MVC 中所有层次的内容。在这个例子中,先编写好 StudentAction.java 文件,以及上图中 webapp 目录中所示的文件。在写好以上代码,同时也能顺利运行之后,我们可以参照之前编写的代码来写模板文件。这里我们来分别看一个 Java 文件和 JSP 的例子。<br>清单 3. ActionTemplate.vm<br><figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div></pre></td><td class="code"><pre><div class="line">#parse ("macro.vm")</div><div class="line"></div><div class="line">@Action("${classNameLowCase}Action")</div><div class="line">public class ${classNameUpCase}Action extends BaseAction{</div><div class="line"> @Autowired</div><div class="line"> public ${classNameUpCase}Dao ${classNameLowCase}Dao;</div><div class="line"> private List<${classNameUpCase}> ${classNameLowCase}s;</div><div class="line"> private ${classNameUpCase} ${classNameLowCase};</div><div class="line">#foreach ($attr in ${attrs})</div><div class="line"> private ${attr[0]} ${attr[1]};</div><div class="line">#end</div><div class="line"> public String ${classNameLowCase}List() {</div><div class="line"> ${classNameLowCase}s = ${classNameLowCase}Dao.retrieveAll${classNameUpCase}s();</div><div class="line"> return "${classNameLowCase}List.jsp";</div><div class="line"> }</div><div class="line"></div><div class="line"> ...</div><div class="line">}</div></pre></td></tr></table></figure></p>
<p>上面的代码展示了一个 Java 类转换成 vm 模板之后的部分内容,完整内容请参考附件。<br>macro.vm 文件中定义了一些使用的宏。JSP 的改造相对于 Java 文件来说稍微有点复杂,因为 JSP 中使用 JSTL 取 request 中的值也是使用${name} 这样的语法,所以想要输出${name} 这样的字符串而不是被模板引擎所替换,则需要使用转义字符,就像这样:\${name}。<br>为了能够让这个文件中的 table 得到复用,我们将这个文件中的表格单独拿出来,使用 #parse 命令来包含。下面是 ListJspTemplate.vm 和 ListTableTemplate.vm 的内容:<br>清单 4. ListJspTemplate.vm<br><figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div></pre></td><td class="code"><pre><div class="line"><span class="tag"><<span class="name">%@</span> <span class="attr">page</span> <span class="attr">language</span>=<span class="string">"java"</span> <span class="attr">contentType</span>=<span class="string">"text/html; charset=UTF-8"</span></span></div><div class="line"> <span class="attr">pageEncoding</span>=<span class="string">"UTF-8"</span>%></div><div class="line"><span class="tag"><<span class="name">%@taglib</span> <span class="attr">prefix</span>=<span class="string">"c"</span> <span class="attr">uri</span>=<span class="string">"http://java.sun.com/jsp/jstl/core"</span> %></span></div><div class="line"><span class="meta"><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"></span></div><div class="line"><span class="tag"><<span class="name">html</span>></span></div><div class="line"><span class="tag"><<span class="name">head</span>></span></div><div class="line"> <span class="tag"><<span class="name">%@</span> <span class="attr">include</span> <span class="attr">file</span>=<span class="string">"includeJS.jsp"</span> %></span></div><div class="line"> <span class="tag"><<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>></span><span class="javascript"></span></div><div class="line"> <span class="keyword">var</span> pageConfig = {</div><div class="line"> <span class="string">"list"</span> : {</div><div class="line"> <span class="string">"action"</span> : <span class="string">"${classNameLowCase}Action!${classNameLowCase}List.action"</span></div><div class="line"> }</div><div class="line"> ...</div><div class="line"> <span class="string">"idName"</span> : <span class="string">"${classNameLowCase}Id"</span></div><div class="line"> };</div><div class="line"> <span class="tag"></<span class="name">script</span>></span></div><div class="line"> <span class="tag"><<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span> <span class="attr">src</span>=<span class="string">"common.js"</span>></span><span class="undefined"></span><span class="tag"></<span class="name">script</span>></span></div><div class="line"><span class="tag"><<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">"Content-Type"</span> <span class="attr">content</span>=<span class="string">"text/html; charset=UTF-8"</span>></span></div><div class="line"><span class="tag"><<span class="name">title</span>></span>${classNameUpCase} List<span class="tag"></<span class="name">title</span>></span></div><div class="line"><span class="tag"></<span class="name">head</span>></span></div><div class="line"><span class="tag"><<span class="name">body</span>></span></div><div class="line"><span class="tag"><<span class="name">h1</span>></span>${classNameUpCase} List<span class="tag"></<span class="name">h1</span>></span></div><div class="line"><span class="tag"><<span class="name">div</span>></span><span class="tag"><<span class="name">button</span> <span class="attr">id</span>=<span class="string">"addButton"</span>></span>Add<span class="tag"></<span class="name">button</span>></span><span class="tag"></<span class="name">div</span>></span></div><div class="line">#parse ("ListTableTemplate.vm")</div><div class="line"><span class="tag"><<span class="name">div</span> <span class="attr">id</span>=<span class="string">"modifyDiv"</span>></span><span class="tag"></<span class="name">div</span>></span></div><div class="line"><span class="tag"><<span class="name">div</span> <span class="attr">id</span>=<span class="string">"addDiv"</span>></span><span class="tag"></<span class="name">div</span>></span></div><div class="line"><span class="tag"></<span class="name">body</span>></span></div><div class="line"><span class="tag"></<span class="name">html</span>></span></div><div class="line">清单 5. ListTableTemplate.vm</div><div class="line">#parse ("macro.vm")</div><div class="line">#set($plus = "status.index+1")</div><div class="line"><span class="tag"><<span class="name">table</span> <span class="attr">border</span>=<span class="string">"1"</span> <span class="attr">style</span>=<span class="string">"width: 100%"</span>></span></div><div class="line"> <span class="tag"><<span class="name">thead</span>></span></div><div class="line"> <span class="tag"><<span class="name">tr</span>></span><span class="tag"><<span class="name">th</span>></span>No.<span class="tag"></<span class="name">th</span>></span>#generateTH($attrs)<span class="tag"></<span class="name">tr</span>></span></div><div class="line"> <span class="tag"></<span class="name">thead</span>></span></div><div class="line"> <span class="tag"><<span class="name">tbody</span>></span></div><div class="line"> <span class="tag"><<span class="name">c:forEach</span> <span class="attr">var</span>=<span class="string">"${classNameLowCase}"</span> <span class="attr">items</span>=<span class="string">"${${classNameLowCase}s }"</span> <span class="attr">varStatus</span>=<span class="string">"status"</span> ></span></div><div class="line"> <span class="tag"><<span class="name">tr</span> ${<span class="attr">classNameLowCase</span>}<span class="attr">Id</span>=<span class="string">"${${classNameLowCase}.id }"</span>></span></div><div class="line"> <span class="tag"><<span class="name">td</span>></span>${${plus}}<span class="tag"></<span class="name">td</span>></span>#generateTD($classNameLowCase $attrs)<span class="tag"><<span class="name">td</span>></span></div><div class="line"> <span class="tag"><<span class="name">button</span> <span class="attr">class</span>=<span class="string">"modifyButton"</span>></span>Modify<span class="tag"></<span class="name">button</span>></span></div><div class="line"> <span class="tag"><<span class="name">button</span> <span class="attr">class</span>=<span class="string">"deleteButton"</span>></span>Delete<span class="tag"></<span class="name">button</span>></span><span class="tag"></<span class="name">td</span>></span><span class="tag"></<span class="name">tr</span>></span></div><div class="line"> <span class="tag"></<span class="name">c:forEach</span>></span></div><div class="line"> <span class="tag"></<span class="name">tbody</span>></span></div><div class="line"><span class="tag"></<span class="name">table</span>></span></div></pre></td></tr></table></figure></p>
<p>在定义好所有的模板文件之后,需要做的是读取这些文件,然后根据这些文件将 model 的数据类型以及名称设置到 context 中,最后将解析出来的内容写到相应的目录中去。这些工作我们放在了一个叫做 VelocityGenerator 的类中来做,它的源码如下:<br>清单 6. TemplateGenerator.java<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">VelocityGenerator</span> </span>{</div><div class="line"></div><div class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>{</div><div class="line"> VelocityEngine ve = <span class="keyword">new</span> VelocityEngine();</div><div class="line"> ve.setProperty(RuntimeConstants.RESOURCE_LOADER, <span class="string">"classpath"</span>);</div><div class="line"> ve.setProperty(<span class="string">"classpath.resource.loader.class"</span>, ClasspathResourceLoader.class.getName());</div><div class="line"></div><div class="line"> ve.init();</div><div class="line"> Template actionTpt = ve.getTemplate(<span class="string">"ActionTemplate.vm"</span>);</div><div class="line"> Template listJspTpt = ve.getTemplate(<span class="string">"ListJspTemplate.vm"</span>);</div><div class="line"> Template addTpt = ve.getTemplate(<span class="string">"AddTemplate.vm"</span>);</div><div class="line"> Template modifyTpt = ve.getTemplate(<span class="string">"ModifyTemplate.vm"</span>);</div><div class="line"> VelocityContext ctx = <span class="keyword">new</span> VelocityContext();</div><div class="line"></div><div class="line"> ctx.put(<span class="string">"classNameLowCase"</span>, <span class="string">"teacher"</span>);</div><div class="line"> ctx.put(<span class="string">"classNameUpCase"</span>, <span class="string">"Teacher"</span>);</div><div class="line"> String[][] attrs = {</div><div class="line"> {<span class="string">"Integer"</span>,<span class="string">"id"</span>},</div><div class="line"> {<span class="string">"String"</span>,<span class="string">"name"</span>},</div><div class="line"> {<span class="string">"String"</span>,<span class="string">"serializeNo"</span>},</div><div class="line"> {<span class="string">"String"</span>,<span class="string">"titile"</span>},</div><div class="line"> {<span class="string">"String"</span>,<span class="string">"subject"</span>}</div><div class="line"> };</div><div class="line"> ctx.put(<span class="string">"attrs"</span>, attrs);</div><div class="line"> String rootPath = VelocityGenerator.class.getClassLoader().getResource(<span class="string">""</span>).getFile() + <span class="string">"../../src/main"</span>;</div><div class="line"> merge(actionTpt,ctx,rootPath+<span class="string">"/java/com/liuxiang/velocity/action/TeacherAction.java"</span>);</div><div class="line"> merge(listJspTpt,ctx,rootPath+<span class="string">"/webapp/teacherList.jsp"</span>);</div><div class="line"> merge(addTpt,ctx,rootPath+<span class="string">"/webapp/teacherAdd.jsp"</span>);</div><div class="line"> merge(modifyTpt,ctx,rootPath+<span class="string">"/webapp/teacherModify.jsp"</span>);</div><div class="line"> System.out.println(<span class="string">"success..."</span>);</div><div class="line"> }</div><div class="line"></div><div class="line"> <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">merge</span><span class="params">(Template template, VelocityContext ctx, String path)</span> </span>{</div><div class="line"> PrintWriter writer = <span class="keyword">null</span>;</div><div class="line"> <span class="keyword">try</span> {</div><div class="line"> writer = <span class="keyword">new</span> PrintWriter(path);</div><div class="line"> template.merge(ctx, writer);</div><div class="line"> writer.flush();</div><div class="line"> } <span class="keyword">catch</span> (FileNotFoundException e) {</div><div class="line"> e.printStackTrace();</div><div class="line"> } <span class="keyword">finally</span> {</div><div class="line"> writer.close();</div><div class="line"> }</div><div class="line"> }</div><div class="line">}</div></pre></td></tr></table></figure></p>
<p>在运行以上代码之后,项目文件夹中将会出现与 Teacher 相关的代码文件。<br>在实际项目中可能不会出现很多这种单张表维护的情况,而且业务逻辑和系统架构会更加复杂,编写模板文件就更加不容易。但是无论多复杂的系统,不同的业务逻辑之间一定或多或少会有相似的代码,特别是在 JSP 和 JS 显示端文件中,因为我们在一个系统中要求显示风格、操作方式一致的时候就免不了会有相似内容的代码出现。在总结这些相似性之后我们还是可以使用 Velocity 来帮助我们生成部分内容的代码,而且即使有一些非共性的内容,我们也可以在生成的代码中继续修改。使用 Velocity 的另外一个好处是生成出来的代码更好维护,风格更加统一。<br>回页首<br>结束语<br>Velocity 可以被应用在各种各样的情景下,本文介绍的只是它的一种用途而已,它还可以被用来做 MVC 结构中的 view 层,或者动态内容静态化等。另外,Velocity 并不是唯一的模板框架,同样很优秀的 Freemarker 也获得了非常广泛的应用,有兴趣的读者可以去深入研究更多的功能和用途。</p>
<p class="article-more-link">
</p>
</div>
<footer class="article-footer clearfix">
<div class="article-catetags">
</div>
<div class="comments-count">
</div>
</footer>
</article>
<article class="post-expand post" itemprop="articleBody">
<header class="article-info clearfix">
<h1 itemprop="name">
<a href="/note/2017/04/15/hello-world/" title="Hello World" itemprop="url">Hello World</a>
</h1>
<p class="article-author">By
<a href="/note/about" title="闫笑南" target="_blank" itemprop="author">闫笑南</a>
<p class="article-time">
<time datetime="2017-04-15T10:43:37.580Z" itemprop="datePublished"> Published 2017-04-15</time>
</p>
</header>
<div class="article-content">
<p>Welcome to <a href="https://hexo.io/" target="_blank" rel="external">Hexo</a>! This is your very first post. Check <a href="https://hexo.io/docs/" target="_blank" rel="external">documentation</a> for more info. If you get any problems when using Hexo, you can find the answer in <a href="https://hexo.io/docs/troubleshooting.html" target="_blank" rel="external">troubleshooting</a> or you can ask me on <a href="https://github.com/hexojs/hexo/issues" target="_blank" rel="external">GitHub</a>.</p>
<h2 id="Quick-Start"><a href="#Quick-Start" class="headerlink" title="Quick Start"></a>Quick Start</h2><h3 id="Create-a-new-post"><a href="#Create-a-new-post" class="headerlink" title="Create a new post"></a>Create a new post</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">$ hexo new <span class="string">"My New Post"</span></div></pre></td></tr></table></figure>
<p>More info: <a href="https://hexo.io/docs/writing.html" target="_blank" rel="external">Writing</a></p>
<h3 id="Run-server"><a href="#Run-server" class="headerlink" title="Run server"></a>Run server</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">$ hexo server</div></pre></td></tr></table></figure>
<p>More info: <a href="https://hexo.io/docs/server.html" target="_blank" rel="external">Server</a></p>
<h3 id="Generate-static-files"><a href="#Generate-static-files" class="headerlink" title="Generate static files"></a>Generate static files</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">$ hexo generate</div></pre></td></tr></table></figure>
<p>More info: <a href="https://hexo.io/docs/generating.html" target="_blank" rel="external">Generating</a></p>
<h3 id="Deploy-to-remote-sites"><a href="#Deploy-to-remote-sites" class="headerlink" title="Deploy to remote sites"></a>Deploy to remote sites</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">$ hexo deploy</div></pre></td></tr></table></figure>
<p>More info: <a href="https://hexo.io/docs/deployment.html" target="_blank" rel="external">Deployment</a></p>
<p class="article-more-link">
</p>
</div>
<footer class="article-footer clearfix">
<div class="article-catetags">
</div>
<div class="comments-count">
</div>
</footer>
</article>
</div>
<div class="openaside"><a class="navbutton" href="#" title="Show Sidebar"></a></div>
<div id="asidepart">
<div class="closeaside"><a class="closebutton" href="#" title="Hide Sidebar"></a></div>
<aside class="clearfix">
<div class="linkslist">
<p class="asidetitle">Links</p>
<ul>
<li>
<a href="记录所学所得" target="_blank" title="我的笔记">我的笔记</a>
</li>
<li>
<a href="549250640@qq.com" target="_blank" title="Jark's Blog">Jark's Blog</a>
</li>
</ul>
</div>
<div class="rsspart">
<a href="/atom.xml" target="_blank" title="rss">RSS</a>
</div>
<div class="weiboshow">
<p class="asidetitle">Weibo</p>
<iframe width="100%" height="119" class="share_self" frameborder="0" scrolling="no" src="http://widget.weibo.com/weiboshow/index.php?language=&width=0&height=119&fansRow=2&ptype=1&speed=0&skin=9&isTitle=1&noborder=1&isWeibo=0&isFans=0&uid=null&verifier=b3593ceb&dpc=1"></iframe>
</div>
</aside>
</div>
</div>
<footer><div id="footer" >
<div class="line">
<span></span>
<div class="author"></div>
</div>
<section class="info">
<p> Hello ,I'm Larry Page in Google. <br/>
This is my blog,believe it or not.</p>
</section>
<div class="social-font" class="clearfix">
<a href="http://weibo.com/2176287895" target="_blank" class="icon-weibo" title="微博"></a>
</div>
<p class="copyright">
Powered by <a href="http://hexo.io" target="_blank" title="hexo">hexo</a> and Theme by <a href="https://github.com/wuchong/jacman" target="_blank" title="Jacman">Jacman</a> © 2017
<a href="/note/about" target="_blank" title="闫笑南">闫笑南</a>
</p>
</div>
</footer>
<script src="/note/js/jquery-2.0.3.min.js"></script>
<script src="/note/js/jquery.imagesloaded.min.js"></script>
<script src="/note/js/gallery.js"></script>
<script src="/note/js/jquery.qrcode-0.12.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.navbar').click(function(){
$('header nav').toggleClass('shownav');
});
var myWidth = 0;
function getSize(){
if( typeof( window.innerWidth ) == 'number' ) {
myWidth = window.innerWidth;
} else if( document.documentElement && document.documentElement.clientWidth) {
myWidth = document.documentElement.clientWidth;
};
};
var m = $('#main'),
a = $('#asidepart'),
c = $('.closeaside'),
o = $('.openaside');
c.click(function(){
a.addClass('fadeOut').css('display', 'none');
o.css('display', 'block').addClass('fadeIn');
m.addClass('moveMain');
});
o.click(function(){
o.css('display', 'none').removeClass('beforeFadeIn');
a.css('display', 'block').removeClass('fadeOut').addClass('fadeIn');
m.removeClass('moveMain');
});
$(window).scroll(function(){
o.css("top",Math.max(80,260-$(this).scrollTop()));
});
$(window).resize(function(){
getSize();
if (myWidth >= 1024) {
$('header nav').removeClass('shownav');
}else{
m.removeClass('moveMain');
a.css('display', 'block').removeClass('fadeOut');
o.css('display', 'none');
}
});
});
</script>
<link rel="stylesheet" href="/note/fancybox/jquery.fancybox.css" media="screen" type="text/css">
<script src="/note/fancybox/jquery.fancybox.pack.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.article-content').each(function(i){
$(this).find('img').each(function(){
if ($(this).parent().hasClass('fancybox')) return;
var alt = this.alt;
if (alt) $(this).after('<span class="caption">' + alt + '</span>');
$(this).wrap('<a href="' + this.src + '" title="' + alt + '" class="fancybox"></a>');
});
$(this).find('.fancybox').each(function(){
$(this).attr('rel', 'article' + i);
});
});
if($.fancybox){
$('.fancybox').fancybox();
}
});
</script>
<!-- Analytics Begin -->
<script>
var _hmt = _hmt || [];
(function() {
var hm = document.createElement("script");
hm.src = "//hm.baidu.com/hm.js?e6d1f421bbc9962127a50488f9ed37d1";
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(hm, s);
})();
</script>
<!-- Analytics End -->
<!-- Totop Begin -->
<div id="totop">
<a title="Back to Top"><img src="/note/img/scrollup.png"/></a>
</div>
<script src="/note/js/totop.js"></script>
<!-- Totop End -->
<!-- MathJax Begin -->
<!-- mathjax config similar to math.stackexchange -->
<!-- MathJax End -->
<!-- Tiny_search Begin -->
<!-- Tiny_search End -->
</body>
</html>
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。