读书人

Velocity帮小弟我们实现页面静态化

发布时间: 2012-09-14 23:00:49 作者: rapoo

Velocity帮我们实现页面静态化
Velocity帮我们实现页面静态化
$name



#set( $condition = true )



数组赋值:

#set( $ints = [1..10])

#foreach( $entry in $ints)

??? $entry

#end



#set( $ints = ["第一个","第二个"])

#foreach( $entry in $ints)

??? $entry

#end

七:#if#else#end

try{

?? Velocity.init("src/velocity.properties");

?? VelocityContext context = new VelocityContext();

? context.put("condition", true);

?? Template template = Velocity.getTemplate("mytemplate.vm");

?? StringWriter sw = new StringWriter();

?? template.merge(context, sw);

?? sw.flush();

?? System.out.println(sw.toString());

}catch( Exception e ){

??? e.printStackTrace();

}

mytemplate.vm内容如下:

#if($condition)

?? 成立

#else

?? 不成立

#end

八:格式化日期

格式化日期必须将velocity-tools-generic-1.4.jar包加入到类路径。

try{

?? Velocity.init("src/velocity.properties");

?? VelocityContext context = new VelocityContext();

?? context.put("now", new Date());

?? context.put("dateformat", new DateTool());

?? Template template = Velocity.getTemplate("mytemplate.vm");

?? StringWriter sw = new StringWriter();

?? template.merge(context, sw);

?? sw.flush();

?? System.out.println(sw.toString());

}catch( Exception e ){

??? e.printStackTrace();

}

mytemplate.vm内容如下:

$dateformat.format("yyyy-MM-dd", $now)

九:输出到文件

try{

??? Velocity.init("src/velocity.properties");

??? VelocityContext context = new VelocityContext();

??? context.put("title", "巴巴运行网");

??? context.put("body", "这是内容");

??? Template template = Velocity.getTemplate("mytemplate.vm");

??? File savefile = new File("E:\\spring\\velocity\\WebRoot\\page\\test.html");

??? if(!savefile.getParentFile().exists()) savefile.getParentFile().mkdirs();

??? FileOutputStream outstream = new FileOutputStream(savefile);

??? OutputStreamWriter writer = new OutputStreamWriter(outstream,"UTF-8");

??? BufferedWriter bufferWriter = new BufferedWriter(writer);

??? template.merge(context, bufferWriter);

??? bufferWriter.flush();

??? outstream.close();

??? bufferWriter.close();

}catch( Exception e ){

??? e.printStackTrace();

}

十:null处理

try{

??? Velocity.init("src/velocity.properties");

??? VelocityContext context = new VelocityContext();

??? context.put("title", null);

??? Template template = Velocity.getTemplate("mytemplate.vm");

??? StringWriter writer = new StringWriter();

??? BufferedWriter bufferWriter = new BufferedWriter(writer);

??? template.merge(context, bufferWriter);

??? bufferWriter.flush();

??? System.out.println(writer.toString());

}catch( Exception e ){

??? e.printStackTrace();

}

mytemplate.vm内容如下:

$title

读书人网 >软件架构设计

热点推荐