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配置后才可使用,例如:
1 <bean 2 class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> 3 <property name="order" value="1"/> 4 <property name="contentNegotiationManager" ref="contentNegotiationManager"/> 5 <property name="viewResolvers"> 6 <list> 7 <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/> 8 <bean 9 class="org.springframework.web.servlet.view.velocity.VelocityViewResolver"> 10 <property name="order" value="0"/> 11 <property name="cache" value="true"/> 12 <property name="prefix" value=""/> 13 <property name="suffix" value=".vm"/> 14 <property name="toolboxConfigLocation" value="/WEB-INF/toolbox.xml"/> 15 <property name="contentType" value="text/html;charset=UTF-8"/> 16 <property name="viewClass" 17 value="com.cnblogs.yjmyzz.utils.VelocityToolbox2View"></property> 18 <property name="attributesMap"> 19 <map> 20 <entry key="sec"> 21 <ref bean="velocitySecurityUtil"/> 22 </entry> 23 <entry key="req"> 24 <ref bean="requestUtil"/> 25 </entry> 26 </map> 27 </property> 28 </bean> 29 <!-- <bean 30 class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 31 <property name="prefix" value="/WEB-INF/views/"/> 32 <property name="suffix" value=".jsp"/> 33 </bean>--> 34 </list> 35 </property> 36 <property name="defaultViews"> 37 <list> 38 <bean id="jsonView" 39 class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"/> 40 <!--<bean id="xmlView" 41 class="org.springframework.web.servlet.view.xml.MarshallingView"> 42 <constructor-arg> 43 <bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller"> 44 <property name="classesToBeBound"> 45 <list> 46 <value>awbprint.mybatis.entity.PrintLayout</value> 47 <value>awbprint.mybatis.entity.PrintItemPosition</value> 48 <value>awbprint.dto.PrintLayoutDto</value> 49 <value>awbprint.dto.ListBean</value> 50 <value>awbprint.dto.UserInfo</value> 51 </list> 52 </property> 53 </bean> 54 </constructor-arg> 55 </bean>--> 56 </list> 57 </property> 58 </bean>