Template Engine Velocity Learning Series #set Directive

Posted by buroy on Tue, 01 Oct 2019 11:17:30 +0200

#set directive

# The set instruction is used to assign values to a variable or object.

Format: # set($var = value)

LHS is a variable. Do not use special characters such as English periods. The test found that # set ($user. name ='zhangsan') and # set (${age} = 18) failed in assignment.

RHS can be variables, string literals, numeric literals, methods, ArrayList s, Map s, expressions.

 

Test case

User object class

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;
    }

}

 

 

Test class TestVelocity

public class TestVelocity {

    public static void main(String[] args) {
        
        VelocityEngine engine = new VelocityEngine();
        // Initialization 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());
    }
    
}

Test template file 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

Output result


john  18  a b c a b c
zhangsan 18 $userTest1

 

Explain:

#set($userTest1 = $user.getAge_())

#set($userTest2 = "$!{user.getAge_()}")

If the $!{user.getAge_()} expression fails to compute, it is placed in double quotation marks, and the assignment empty string will not be assigned outside.

When using # set, the literal value of a string, if placed in double quotation marks, will be parsed and placed in single quotation marks, which will be treated as literal.

#set($test1 = "$userName")

#set($test2 = '$userName')

$test1=Character string zhangsan,$test2=Character string $userName. 

Topics: Java encoding Apache