#set指令
#set指令用于向一个变量或者对象赋值。
格式: #set($var = value)
LHS是一个变量,不要使用特殊字符例如英文句号等,不能用大括号括起来。测试发现#set($user.name = ‘zhangsan’),#set(${age} = 18)均赋值失败。
RHS可以是变量、字符串字面值、数字字面值、方法、ArrayList、Map、表达式。
测试案例
User对象类
public class User { private String name; private int age; public User(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
测试类TestVelocity
public class TestVelocity { public static void main(String[] args) { VelocityEngine engine = new VelocityEngine(); // 初始化VelocityEngine engine.setProperty("resource.loader", "file"); engine.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.FileResourceLoader"); engine.setProperty("input.encoding", "utf8"); engine.setProperty("output.encoding", "utf8"); engine.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, "D:\\conf"); engine.init(); Template template = engine.getTemplate("hellovelocity.vm"); VelocityContext ctx = new VelocityContext(); ctx.put("user", new User("zhangsan", 18)); StringWriter stringWriter = new StringWriter(); template.merge(ctx, stringWriter); System.out.println(stringWriter.toString()); } }
测试模板文件 hellovelocity.vm
#set($name = 'john') #set($age = 18) #set($array = ['a', 'b', 'c']) #set($map = {'a' : 'a', 'b' : 'b', 'c' : 'c'}) #set($userName = "$!{user.getName()}") #set($userAge = "$!{user.getAge()}") #set($userTest1 = $user.getAge_()) #set($userTest2 = "$!{user.getAge_()}") $name $age $array.get(0) $array.get(1) $array.get(2) $map.get('a') $map.get('b') $map.get('c') $userName $userAge $userTest1 $userTest2
输出结果
john 18 a b c a b c zhangsan 18 $userTest1
说明:
#set($userTest1 = $user.getAge_())
#set($userTest2 = “$!{user.getAge_()}”)
右边$!{user.getAge_()}表达式计算失败情况下,放在双引号里面,赋值空串,放在外面将不会赋值。
在使用#set时,字符串的字面值如果放在双引号里,将会被解析,放在单引号里面,将会被当做字面量。
#set($test1 = "$userName") #set($test2 = '$userName') $test1=字符串zhangsan,$test2=字符串$userName。