一 Java模板技术-velocity
需要lib:
velocity-1.6.3.jar,
commons-lang-2.2.jar,
commons-collections-3.2.jar
1.
// 配置初始化参数
Properties props = new Properties();
props.setProperty(Velocity.INPUT_ENCODING, "utf-8"); //input.encoding
props.setProperty(Velocity.RESOURCE_LOADER, "class"); // resource.loader
props.setProperty("class.resource.loader.class", //
"org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
// 初始化并取得Velocity引擎
VelocityEngine ve = new VelocityEngine(props);
// 取得velocity的模版
Template template = ve.getTemplate("helloVelocity.vm");
// Template实例的获取方式也可以用下面两行代码
// Velocity.init(props);
// Template template = Velocity.getTemplate("helloVelocity.vm");
// 取得velocity的上下文context
VelocityContext context = new VelocityContext();
// 把数据填入上下文
context.put("owner", "Unmi");
context.put("bill", "1000");
context.put("type", "报销单");
context.put("date", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
// 输出流,你可以自由控制输出到哪,String、File、Socket 等
Writer writer = new PrintWriter(System.out);
// 转换输出
template.merge(context, writer);
writer.flush();
2.
InputStream is = BaseVelocityTask.class.getClassLoader()
.getResourceAsStream("velocity.properties");
Properties p = new Properties();
p.load(is);
is.close();
Velocity.init(p);
velocity.properties:
input.encoding = UTF-8 //Velocity.INPUT_ENCODING
output.encoding = UTF-8 //Velocity.OUTPUT_ENCODING
default.contentType = text/html;charset=UTF-8 //
resource.loader = file / /Velocity.RESOURCE_LOADER
file.resource.loader.class = org.apache.velocity.runtime.resource.loader.FileResourceLoader
file.resource.loader.path =
E:\\server\\tomcat6020\\webapps\\template
//Velocity.FILE_RESOURCE_LOADER_PATH
VelocityContext context = new VelocityContext();
context.put("abcGames",obj);
Template template = Velocity.getTemplate(MessageFormat.format(vm_path, getTemplateName()));
for(Object key : context.getKeys()){
context.remove(key);
}
// this.process();
OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(MessageFormat.format(html_path, getTemplateName())), "UTF-8");
template.merge(context, writer);
writer.flush();
writer.close();
二 velocity模板规则
1 简单: $str
2 javabean的vlt语法:
3.关于list和hashmap的显示:
4.此时,如果要列出hashMap中key=“NARR”的值,可以如下:
5.如果要全部列出hashmap的key-value,可以如下:
6.spring框架已经提供了对velocity的支持,在视图方面可以取代jsp。具体配置,可以参考“spring in action”
(1)Velocity http://velocity.apache.org/ (and WebMacro, FreeMarker.. etc)
(2)Tapestry http://jakarta.apache.org/tapestry/
(3)Echo http://sourceforge.net/projects/echo
(4)Cocoon (XML + XSLT) http://cocoon.apache.org/
(5)XMLC(Static DOM) http://xmlc.enhydra.org/
(6)NekoHTML (Dynamic DOM) http://www.apache.org/~andyc/neko/doc/html/
(7)JDynamiTe(PHP Template Port)https://sourceforge.net/projects/jdynamite
fastm