1.pom.xml
<!-- Freemarker模板引擎 SpringBoot整合依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
2.application.yml
server:
port: 80
servlet:
context-path: /happyCode
spring:
http:
encoding:
force: true
charset: UTF-8
freemarker:
allow-request-override: false
#缓存
cache: false
check-template-location: true
charset: UTF-8
content-type: text/html; charset=utf-8
expose-request-attributes: false
expose-session-attributes: false
expose-spring-macro-helpers: false
#后缀
suffix: .ftl
#模板加载位置
template-loader-path: classpath:/templates
3.src/main/resources
创建templates目录
创建文件
helloWorld.html.ftl
<#-- uncap_first首字母转小写 cap_first首字母转大写 -->
${date} hello world ${name?cap_first}
Controller 方法定义
/*@Resource
//Configuration cfg;*/
@RequestMapping("/{ftlName}")
public ModelAndView helloWorldFreemarker(@PathVariable("ftlName") String name, ModelAndView mv) throws Exception{
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
mv.addObject("name", "Freemarker");
mv.addObject("date", formatter.format(new Date()));
mv.setViewName("helloWorld.html");
/*String basePath = this.getClass().getClassLoader().getResource("").toURI().getPath();
Writer writer = new FileWriter(new File(basePath)+"\\helloWorld.html");
Template template = cfg.getTemplate("helloWorld.html.ftl");
Map<String,String> dataModel = new HashMap<String,String>();
dataModel.put("name", "Freemarker");
dataModel.put("date", formatter.format(new Date()));
template.process(dataModel, writer);*/
return mv;
}