Java Velocity模板引擎-简单字符串生成

利用Velocity模板引擎,可以将一段字符串作为模板,通过模板内置变量来生成代码。

package src;

import java.io.StringWriter;
import java.util.Date;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;

public class Main {

    public static void main(final String[] args) {
        try {
            VelocityEngine velocityEngine = new VelocityEngine();

            velocityEngine.init();
    
            Velocity.init();
    
            /* lets make a Context and put data into it */    
            VelocityContext context = new VelocityContext();    
            context.put("name", "Velocity");
            context.put("project", "Jakarta");
            context.put("now", new Date()); 
    
            /* lets make our own string to render */    
            String str = "We are using $project $name to render this. 中文测试  $!dateFormatUtils.format($!now,'yyyy-MM-dd')";
            StringWriter stringWriter = new StringWriter();
            Velocity.evaluate(context, stringWriter, "mystring", str);
            System.out.println(" string : " + stringWriter); 
            
        } catch (final Exception e) {
            System.out.print("系统异常:" + e.getMessage());
            e.printStackTrace();
        }
    }

}

运行结果

 程序用vscode运行的,完整代码下载

猜你喜欢

转载自blog.csdn.net/a497785609/article/details/130007990