Velocity之WEB(Object,List,Map)

参考资料
1 使用 Velocity 实现客户端和服务器端模板
http://www.ibm.com/developerworks/cn/java/j-velocity/
2 velocity整合servlet
http://www.blogjava.net/sxyx2008/archive/2010/11/11/337819.html
3 Velocity学习之Servlet初体验
http://jzhua.iteye.com/blog/311399
4 Velocity初体验
http://blog.csdn.net/zyk220/article/details/1927298
5 Velocity用户手册---中文版
http://blog.csdn.net/zyk220/article/details/1927304
Velocity是一个基于java的模板引擎(template engine)。它允许任何人仅仅简单的使用模板语言(template language)来引用由java代码定义的对象.
一 环境:Win7 64 + Eclipse3.7 + Tomcat6 + JDK1.6
二 工程图片如下:
Velocity之WEB(Object,List,Map)
三 具体实现
1 MyVelocityServlet3.java
package velocity;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.Template;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.context.Context;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.servlet.VelocityServlet;

import service.UserService;
import bean.User;

@SuppressWarnings("deprecation")
public class MyVelocityServlet3 extends VelocityServlet {
	private static final long serialVersionUID = 1L;

	public MyVelocityServlet3() {

	}
	
	@Override
    protected void setContentType(HttpServletRequest request,
            HttpServletResponse response) {
        response.setContentType("text/html;charset=utf-8");
    }

	protected Properties loadConfiguration(ServletConfig config)
			throws IOException, FileNotFoundException {
		/*
		 * 得到属性配置文件并load它
		 */
		String propsFile = config.getInitParameter(INIT_PROPS_KEY);
		Properties p = new Properties();
		if (propsFile != null) {
			String realPath = getServletContext().getRealPath(propsFile);
			if (realPath != null) {
				propsFile = realPath;
			}
			p.load(new FileInputStream(propsFile));
		}
		/*
		 * 设置velocity日志文件在web应用中的位置
		 */
		String log = p.getProperty(Velocity.RUNTIME_LOG);
		if (log != null) {
			log = getServletContext().getRealPath(log);
			if (log != null) {
				p.setProperty(Velocity.RUNTIME_LOG, log);
			}
		}
		/*
		 * 设置模板文件在web应用中的位置
		 */
		String path = p.getProperty(Velocity.FILE_RESOURCE_LOADER_PATH);
		if (path != null) {
			path = getServletContext().getRealPath(path);
			if (path != null) {
				p.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, path);
			}
		}
		return p;
	}

	public Template handleRequest(HttpServletRequest request,
			HttpServletResponse response, Context ctx) {
		
		//普通变量演示
		String userName = "咫尺天涯";
		ctx.put("userName", userName);
		int userAge = 30;
		ctx.put("userAge", userAge);	
		String blog = "http://liuzidong.iteye.com/";
		ctx.put("userBlog", blog);
		
		//JavaBean演示.
		double money = 3999.89;
		ctx.put("user", new User(userAge,userName,blog,money,true));
		
		//List
		List list = new ArrayList();
		list.add("天涯");
		list.add(30);
		list.add(money);
		ctx.put("list",list);
		
		//List<User>
		List<User> users = new ArrayList<User>();
		users.add(new User(23,"david",blog,money,true));
		users.add(new User(18,"天涯",blog,646.89,true));
		users.add(new User(32,"jack",blog,2323.45,false));
		ctx.put("users",users);
		
		//Map
		Map map = new HashMap();
		map.put("1", "a");
		map.put("2", "b");
		map.put("3", "c");
		ctx.put("map", map);
		
		//Map<User>
		Map<String,User> userMap = new HashMap<String,User>();
		userMap.put("1",new User(23,"david",blog,money,true));
		userMap.put("2",new User(18,"天涯",blog,646.89,true));
		userMap.put("3",new User(32,"jack",blog,2323.45,false));
		ctx.put("userMap", userMap);
		
		//调用方法
		ctx.put("userService", new UserService());
		/*
		 * 获取模板对象,有三种可能产生的异常
		 */
		Template outty = null;
		try {
			outty = getTemplate("demo3.vm");
		} catch (ParseErrorException pee) {
			System.out.println("SampleServlet : parse error for template "
					+ pee);
		} catch (ResourceNotFoundException rnfe) {
			System.out.println("SampleServlet : template not found " + rnfe);
		} catch (Exception e) {
			System.out.println("Error " + e);
		}
		return outty;
		
	}
}

2 velocity.properties
# 指定模板文件存放目录  
file.resource.loader.path = templates
# 指定日志文件位置
runtime.log = log/velocity.log 
input.encoding=utf-8
output.encoding=utf-8

3 demo3.vm
<html>
  <head><title>Demo velocity page</title></head>
  <body bgcolor="#ffffff">
    <br>姓名:$userName,年龄:$userAge,$userName的博客:<a href="$userBlog">$userBlog</a>
	<br>年龄if elseif else end使用:
	#if($userAge < 18)
		未成年
	#elseif($userAge >= 18 && $userAge <= 30)
		青年
    #elseif($userAge > 30 && $userAge <= 60)
		中年
	#else
		老年
	#end
	<br>JavaBean演示:$user.getUsername(),$user.age,$user.blog,$user.momey,#if($user.xb)男#else女#end;
	<br> List:
		<ui>
		#foreach($index in $list)
			<li>$index</li>
		#end
        </ui>
	<br> List&lt;User&gt;:	
		<ui>
		#foreach($user in $users)
            <li>$user.age,$user.username,<a href="$user.blog">$user.blog</a>,#if($user.xb)男#else女#end</li>
		#end
        </ui>	
	<br> Map:	
		<ui>
		#foreach($entity in $map.entrySet())
            <li>$entity.key,$entity.value</li>
		#end
        </ui>	
	<br> Map&lt;User&gt;:	
		<ui>
		#foreach($entity in $userMap.entrySet())
            <li>$entity.key,$entity.value.age,$entity.value.username,<a href="$entity.value.blog">$entity.value.blog</a>,#if($entity.value.xb)男#else女#end</li>
		#end
        </ui>	
	<br> 调用类方法(好强大^_^):$userService.getUserName('咫尺天涯');		
		
    <br>变量<br><textarea rows="4" cols="60">
	  变量的简略标记是有一个前导"$"字符后跟一个VTL标识符(Identifier.)标识符必须以一个字母开始(a...z或A...Z).
	  剩下的字符将由以下类型的字符组成:字母(a...z,A...Z) 数字(0...9) 连字符("-")下划线("_")
	</textarea>
	<br>#set ( $a ="Velocity") Hello $a World! 
	<br>使用$!文本框的初始值就不会是myuserName而是空值<input type="text" value="$!myuserName"/>
	<br>VTL中使用"/”作为逃逸符:<br>
	#set( $email ="[email protected]")
   <br> $email
   <br>/$email
   <br>//$email
   <br>///$email
	
	#macro ( d )
      <ui>
		<li >1</li>
		<li >2</li>
		<li >3</li>
      </ui>
	#end
	
	<br>macro使用:#d()
	<br>
	  #macro ( tablerows $color $somelist $mycolor)
        #foreach ( $something in $somelist )		  
          <tr>
			<td>$velocityCount</td>	
			 #set ( $tdColor = "green")
			 #if($velocityCount % 2 == 0)
				 #set ( $tdColor = $color)
			 #else
				#set ( $tdColor = $mycolor)
			 #end	
			<td bgcolor=$tdColor>$something</td>
		  </tr>
        #end
      #end
	<br>macro常见应用:隔行变色
	#set ( $greatlakes = [ "Superior", "Michigan", "Huron", "Erie", "Ontario" ] )
    #set ( $color = "blue")
	#set ( $color2 = "red")
    <table>
     #tablerows($color $greatlakes $color2)
   </table>	
	
   <br>math   在模板中可以使用Velocity内建的算术函数,如:加、减、乘、除
   <br>
    #set ($numer = 6)
	#set ( $foo = $numer + 3 )$foo<br>
    #set ( $foo = $numer - 4 )$foo<br>
    #set ( $foo = $numer * 6 )$foo<br>
    #set ( $foo = $numer / 2 )$foo<br>
	#set ( $foo = $numer % 5 )$foo<br>	
  </body>
</html> 

4 web.xml
<servlet>
    <description></description>
    <display-name>MyVelocityServlet3</display-name>
    <servlet-name>MyVelocityServlet3</servlet-name>
    <servlet-class>velocity.MyVelocityServlet3</servlet-class>
    <init-param>
	   <param-name>org.apache.velocity.properties</param-name>
	   <param-value>/WEB-INF/classes/velocity.properties</param-value>
	</init-param>
	<load-on-startup>1</load-on-startup> 
  </servlet>
  <servlet-mapping>
    <servlet-name>MyVelocityServlet3</servlet-name>
    <url-pattern>/velocity3</url-pattern>
  </servlet-mapping>

具体参见代码注释^_^

你可能感兴趣的:(velocity)