velocity 实例



通过velocity对字符串进行格式化输出
package cn.com.ld.test.velocity;

import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import junit.framework.Assert;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.context.Context;
import org.junit.Before;
import org.junit.Test;

public class VelocityTest{
	
	private final static String TEMPLATE = "src/cn/com/ld/test/velocity/template.properties" ;
	
	private Velocity  v = null ;
	@Before
	public void init(){
		v = new Velocity();
		Properties p = new Properties();
		v.init(TEMPLATE);
	}
	
	@Test
	public void testA(){
		System.out.println("testa0:"+StringEscapeUtils.unescapeJava(String.valueOf(v.getProperty("name"))));
		//Escape.getText("---------------"+(String) v.getProperty("name")) ;
	}
	
	
	@Test
	public void testEvaluate(){
		Context context = new VelocityContext();
		context.put("name", "java小生");
		StringWriter sw = new StringWriter();
		Assert.assertEquals(true, (v.evaluate(context, sw, "", "hello,$name")));
		System.out.println(sw.toString());
		
	}
	
	@Test
    public void testMergeUnContainKey() throws UnsupportedEncodingException{
    	Map<String,Object> context = new HashMap<String,Object>();
		context.put("name", "java小生");
		VelocityContext vt = new VelocityContext(context);
		StringWriter sw = new StringWriter();
		Template t = Velocity.getTemplate(TEMPLATE);
		t.merge(vt, sw);
		System.out.println(StringEscapeUtils.unescapeJava(sw.toString()));
    }
}



2:properties文件如下
username : $name
name=java\u5c0f\u751f

你可能感兴趣的:(velocity 实例)