Velocity Quick Start [2] – 從模板產生

來源:互聯網
上載者:User

源檔案

package nc.jonathan.velocity;

import java.io.StringWriter;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;

/**
 *<p> 第二個velocity學習類 </p>
 *
 *<p> 採用預設初始化設定,解析預設位置模版, 輸出到字串</p>
 *
 * Create on 2006-4-3 10:49:41
 *
 * @author Jonathan Q. Bo
 * @version 1.0 valocity study
 */

public class SecondExample {
 public static void main(String[] args){
  try {
   /* 初始化運行時引擎, 預設初始化 */
   Velocity.init();
   
   /* 建立context, 並放入資料*/
   VelocityContext context = new VelocityContext();
   context.put("project","jonathan's velocity");
   context.put("name","first example");
   
   /* 解析後資料的輸出目標,java.io.Writer的子類 */
   StringWriter w = new StringWriter();
   
   /* 進行解析 */
   //Velocity.mergeTemplate("secondtemplate.vm",context,w);
   Velocity.mergeTemplate("secondtemplate.vm","gb2312",context,w);
   
   System.out.println(w);
  } catch (ResourceNotFoundException e1) {
   System.out.println("## 源檔案不存在!");
   e1.printStackTrace();
  } catch (ParseErrorException e2) {
   System.out.println("## 解析檔案錯誤!");
   e2.printStackTrace();
  } catch (MethodInvocationException e3) {
   System.out.println("## 方法調用異常!");
   e3.printStackTrace();
  } catch (Exception e4){
   System.out.println("## 其他錯誤!");
   e4.printStackTrace();
  }
 }
}

模板檔案

We are using template.vm to generate $project $name

輸出結果
We are using template.vm to generate jonathan's velocity first example

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.