寻找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,但是两个jsp之间不能共享变量

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

     3.判断字符是否相等
       

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

 

    4.javascript中使用vm变量
        


 
    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)
                    
计数开始$velocityCount
#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)

  • $n.Id
#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 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();
	        } 
  

 
  

你可能感兴趣的:(java开发,velocity,JSP,log4j,Servlet,Apache)