JAVA velocity模板引擎使用實例

velocity使用1.7版本。 在win7下使用intelliJ IDEA建立一基於tomcat的web app項目,命名爲todo_web,設置path爲/todo,導入velocity相關jar包。只導入velocity-1.7.jar這個包可能會報錯,根據提示再導入velocity自帶的其他包。 項目結構如下:



測試Tomcat

index.jsp內容如下:

複製代碼代碼如下:

<%-- Created by IntelliJ IDEA. --%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title></title>
  </head>
  <body>
           <%
               out.print("hi,todo");
           %>
  </body>
</html>

HelloWorld.java內容如下:
複製代碼代碼如下:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;    
public class HelloWorld extends HttpServlet {
    /**
     *
     * @param request
     * @param response
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Hi!</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Hello World!!!</h1>");
        out.println("</body>");
        out.println("</html>");
    }
}

在web.xml中加入以下內容:
複製代碼代碼如下:

<servlet>
    <servlet-name>hi</servlet-name>
    <servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>hi</servlet-name>
    <url-pattern>/hi</url-pattern>
</servlet-mapping>

運行項目,在http://localhost:8080/todo和http://localhost:8080/todo/hi中可以看到效果。


使用velocity

下面開始使用velocity模板引擎,在src下建立目錄templates,在templates目錄下建立文件test.vm,內容如下:

複製代碼代碼如下:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
#set( $this = "Velocity")
$this is great!  <br/>
$name  <br/>
hi  , i am letian
<h1>你好</h1>
</body>
</html>

在src目錄下新建java文件MyVelocity01.java:
複製代碼代碼如下:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.VelocityContext;
import java.util.Properties;
public class MyVelocity01 extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8"); 
        PrintWriter out = response.getWriter(); 
        Properties properties=new Properties();
        properties.setProperty("resource.loader", "class");
        properties.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        //properties.setProperty("input.encoding", "UTF-8");
        //properties.setProperty("output.encoding", "UTF-8");
        properties.setProperty(Velocity.ENCODING_DEFAULT, "UTF-8");
        properties.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
        properties.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
        VelocityEngine velocityEngine = new VelocityEngine(properties);
        VelocityContext context=new VelocityContext();
        context.put("name", "test");
        StringWriter sw = new StringWriter();
        velocityEngine.mergeTemplate("templates/test.vm", "utf-8", context, sw);
        //velocityEngine.mergeTemplate("templates/test.vm", "utf-8", context, sw);      //這樣就會出現兩次
        out.println(sw.toString());
    }
}

配置web.xml:

複製代碼代碼如下:

<!--MyVelocity-->
<servlet>
    <servlet-name>ve</servlet-name>
    <servlet-class>MyVelocity01</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>ve</servlet-name>
    <url-pattern>/ve</url-pattern>
</servlet-mapping>

重新部署,瀏覽器訪問http://localhost:8080/todo/ve可以看到效果。

簡單介紹velocity

velocity是一個基於java的模板引擎,有三種文件加載模板方式: 1、從文件路徑加載 2、從類路徑(MyVelocity01.java使用該方法) 3、從jar文件加載 開始接觸velocity時可能會在加載模板上遇到問題。

如何向模板文件傳遞變量: 模板本身可以定義變量,例如在test.vm中定義了變量$this,java代碼也可以給模板傳遞變量,例如test.vm中的變量$name便是VelocityContext實例傳遞過去的。同時velocity也支持迭代對象,例如: 我們在MyVelocity01.java中導入java.util.Vector,將代碼:

複製代碼代碼如下:

context.put("name", "test");

改爲:
複製代碼代碼如下:

Vector v = new Vector();  
v.addElement("Harry");  
v.addElement("John");  
String[] names = {"Harry", "John"};
context.put("names1", v);
context.put("names2", names);

將test.vm內容改爲:
複製代碼代碼如下:

<h1>hello</h1>
#foreach($name in $names1)
    $name   <br/>
#end
#foreach($name in $names2)
    $name   <br/>
#end

velocity還支持map容器,支持使用#include("")引入靜態模板,#parse("模板名")引入動態模板。

如果想不開要用java MVC寫網站的話,使用servlet + velocity是一個小巧靈活的選擇。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章