velocity基本用法

时间:2021-12-12 06:01:30

1.定义变量

#set($root="www");
#set($name="index.vm");
#set($tmp="$root/$name") //$tmp是 www/index.vm
使用变量时如果为空会原样输出,$tmp,所以安全的写法是$!tmp

2.循环
#foreach($item in $lst)
  $velocityCount
#end

#foreach($key in $map.keyset())
  $map.get($key)
#end

3.条件语句
#if(...)
#elseif(...)
#else
#end 
4.宏(理解为函数)
定义:
#macro(名称 参数1 参数2)
#end

调用:
#名称(参数1 参数2)

5.toolbox.xml配置(可以把一些常用工具类放在这里)

<toolbox>
<tool>
<key>number</key>
<scope>application</scope>
<class>org.apache.velocity.tools.generic.NumberTool</class>
</tool>
</toolbox>

如果使用spring,需要再spring配置后才可使用,例如:

 <bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1"/>
<property name="contentNegotiationManager" ref="contentNegotiationManager"/>
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
<bean
class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
<property name="order" value="0"/>
<property name="cache" value="true"/>
<property name="prefix" value=""/>
<property name="suffix" value=".vm"/>
<property name="toolboxConfigLocation" value="/WEB-INF/toolbox.xml"/>
<property name="contentType" value="text/html;charset=UTF-8"/>
<property name="viewClass"
value="com.cnblogs.yjmyzz.utils.VelocityToolbox2View"></property>
<property name="attributesMap">
<map>
<entry key="sec">
<ref bean="velocitySecurityUtil"/>
</entry>
<entry key="req">
<ref bean="requestUtil"/>
</entry>
</map>
</property>
</bean>
<!-- <bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>-->
</list>
</property>
<property name="defaultViews">
<list>
<bean id="jsonView"
class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"/>
<!--<bean id="xmlView"
class="org.springframework.web.servlet.view.xml.MarshallingView">
<constructor-arg>
<bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>awbprint.mybatis.entity.PrintLayout</value>
<value>awbprint.mybatis.entity.PrintItemPosition</value>
<value>awbprint.dto.PrintLayoutDto</value>
<value>awbprint.dto.ListBean</value>
<value>awbprint.dto.UserInfo</value>
</list>
</property>
</bean>
</constructor-arg>
</bean>-->
</list>
</property>
</bean>