读书人

寻觅velocity模板的使用技巧

发布时间: 2012-10-26 10:30:59 作者: rapoo

寻找velocity模板的使用技巧

一.内置对象(没有配置toolbox情况)
??? 1.HttpServletRequest -------------------------$request
??? 2.HttpServletResponse -----------------------$response
??? 3.HttpSession ----------------------------------$session
二.layout
???? 1.http://qieqie.iteye.com/blog/65028
三.vm语法
??? 1.parse与include
?????? parse-------动态包含vm文件,文件间可共享vm变量
?????? include-----静态引入,不对vm表达式做解析
???????jsp中的<jsp:include page="" />也是动态引入jsp,但是两个jsp之间不能共享变量

???? 2.减法运算
?????? #set($index=$index-1)????? ##这条语法会出错,改成如下:
?????? #set($index=$index - 1)??? ##在减号前后各加一个空格

???? 3.判断字符是否相等
???????

#if($a==$b) <div>success</div>#end     ##如果$a或$b为空,这条语句有语法错误,改成如下:#if("$a"=="$b") <div>success</div>#end 或者#if($a&&$b&$a==$b) <div>success</div>#end 

?

??? 4.javascript中使用vm变量
????????

<script>         #if($a&&$a.length()>0)            var a="$a"            alert(a);        #end</script>

?
??? 5. foreach循环的counter(循环次数计数)
??????? 在velocity.properties中有一段配置
??????? directive.foreach.counter.name = velocityCount?????????????? ##定义变量名称
??????? directive.foreach.counter.initial.value = 1????????????????????????? ##定义计算从1开始累加
??????? 例如:
????????

#foreach($n in [1..10])              #if($velocityCount==$n)                    <div>计数开始$velocityCount</div>              #end          #end

?
四.模板的解析
??? 1.模板文件的merge
???????

        StringWriter writer = new StringWriter();        Map context=new HashMap();        context.put("vm_prop1","12");        VelocityContext model = new VelocityContext(context);        model.put("vm_prop2", "14");           try {             Template tpl = Velocity.getTemplate("portal.vm");            tpl.merge(model, writer);            writer.close();        } catch (Exception e) {             log.error("Can't merge portal.vm", e);         }        log.info(writer.toString);

?
??????? 对portal.vm中的vm_prop1和vm_prop2两个变量赋值并解析返回writer

??? 2.字符串的merge????
?????

public static boolean evaluate(org.apache.velocity.context.Context context, Writer writer, String logTag, Reader reader) throws ParseErrorException, MethodInvocationException, ResourceNotFoundException, IOException {        SimpleNode nodeTree = null;        try {              nodeTree = RuntimeSingleton.parse(reader, logTag, false);        } catch (ParseException pex) {              throw new ParseErrorException(pex.getMessage());        }        if (nodeTree != null) {              InternalContextAdapterImpl ica = new InternalContextAdapterImpl(context);              ica.pushCurrentTemplateName(logTag);        try {            try {                 nodeTree.init(ica, RuntimeSingleton.getRuntimeServices());            } catch (Exception e) {                 RuntimeSingleton.error("Velocity.evaluate() : init exception for tag = " + logTag + " : " + e);            }            nodeTree.render(ica, writer);        } finally {            ica.popCurrentTemplateName();         }    return true;   }   return false;}

?


StringReader reader = new StringReader("#foreach($n in $list) <ul><li>$n.Id</li></ul>#end");
reader为读取一个vm文件里的内容,包含vm表达式,logTag为这一串字符串赋予一个模板名称(如:"a.vm")通过context对vm表达式赋值,并对reader读取的字符串进行解析,返回给writer

五.servlet应用
??? 1.可增加一个Listener,在这个Listener初始化velocity的一些配置,这样避免每个servlet都需要初始化velocity

??????????

                        Properties props = new Properties();        try {            File conf = new File(event.getServletContext().getRealPath("WEB-INF/velocity.properties"));            props.load(new FileInputStream(conf));        }catch (Exception e) {????????????                 e.printStackTrace();????????                }        try {            Iterator<Object> iter = props.keySet().iterator();            while(iter.hasNext()) {                String key = (String) iter.next();                Velocity.setProperty(key,props.getProperty(key));            }            Velocity.setProperty( RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS,                "org.apache.velocity.runtime.log.SimpleLog4JLogSystem" );            Velocity.setProperty("runtime.log.logsystem.log4j.category", "sys.velocity");            Velocity.setProperty("resource.loader","file");            Velocity.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, event.getServletContext().getRealPath("/WEB-INF/templates"));            Velocity.setProperty("parser.pool.size","3");            Velocity.setProperty("velocimacro.library","macro_default.vm,macro_expopo.vm");            Velocity.init();        } catch (Exception e) {            e.printStackTrace();        }

?
??

读书人网 >软件架构设计

热点推荐