<dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity</artifactId> <version>1.7</version> </dependency> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-tools</artifactId> <version>2.0</version> </dependency>
template.vmhtml
<html> <body> ${name}, hello world! Hello world, $name! </body> </html>
Demo.javajava
public class Demo { public static void main(String[] args) { try { // 設置模板路徑 Properties properties = new Properties(); properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, "d:\\"); // 初始化Velocity引擎; VelocityEngine engine = new VelocityEngine(); engine.init(properties); // 構造上下文環境,壓入須要用到的變量 VelocityContext context = new VelocityContext(); context.put("name", "Velocity"); // 加載模板 Template template = engine.getTemplate("template.vm"); // 根據上下文解析模板與數據 StringWriter writer = new StringWriter(); template.merge(context, writer); // 輸出 System.out.println(writer.toString()); } catch (ResourceNotFoundException e) { e.printStackTrace(); } catch (ParseErrorException e) { e.printStackTrace(); } catch (MethodInvocationException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }
輸出:apache
看別人簡單試了一下,記錄下來!spa