提前声明这是一个最小环境,我最烦学个小模板还把 hibernate, spring security 加上去,唯恐天下不乱,
我是不喜欢velocity的,但公司要用,spring boot高版本有放弃对velocity的支持,这里是低版本的
我用的是idea项目结构为
pom.xml
4.0.0 com.aliyun demo 0.0.1-SNAPSHOT jar demo Demo project for Spring Boot org.springframework.boot spring-boot-starter-parent 1.4.2.RELEASE UTF-8 UTF-8 1.8 org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-starter-velocity org.springframework.boot spring-boot-starter-test test junit junit 4.12 test org.springframework.boot spring-boot-maven-plugin
application.properties
spring.velocity.cache= falsespring.velocity.charset=UTF-8spring.velocity.check-template-location=truespring.velocity.content-type=text/htmlspring.velocity.enabled=truespring.velocity.resource-loader-path=/templatesspring.velocity.prefix=/templates/spring.velocity.suffix=.vm
index.vm为
亲爱的${toUserName},你好! ${message}祝:开心! ${fromUserName}55 ${time}
DemoApplication.java
package com.aliyun.demo;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import java.util.Map;@Controller@SpringBootApplicationpublic class DemoApplication { @RequestMapping("/") public String velocityTest(Map map){ map.put("message", "这是测试的内容。。。"); map.put("toUserName", "张三1"); map.put("fromUserName", "老许"); return "index"; } public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); }}
DemoApplicationTests.java
package com.aliyun.demo;import org.apache.velocity.app.VelocityEngine;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringRunner;import org.springframework.ui.velocity.VelocityEngineUtils;import java.util.HashMap;import java.util.Map;@RunWith(SpringRunner.class)@SpringBootTestpublic class DemoApplicationTests { @Test public void contextLoads() { } @Autowired VelocityEngine velocityEngine; @Test public void velocityTest(){ Mapmodel = new HashMap (); model.put("message", "这是测试的内容。。。"); model.put("toUserName", "张三"); model.put("fromUserName", "老许"); System.out.println(VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "/templates/index.vm", "UTF-8", model)); }}
没有废话