- 添加pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
- application.properties相关配置
#整合freemarker
spring.freemarker.cache=false
spring.freemarker.charset=UTF-8
spring.freemarker.content-type=text/html
spring.freemarker.template-loader-path=classpath:/templates/fm/
spring.freemarker.suffix=.ftl
spring.freemarker.allow-request-override=false
spring.freemarker.check-template-location=true
spring.freemarker.expose-request-attributes=true
spring.freemarker.expose-session-attributes=true
- Controller类
package com.example.demo.controller;
import java.util.HashMap;
import java.util.Map;import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;@Controller
@RequestMapping("/fm")
public class FreemarkerController {@RequestMapping("/index")
public Object index(ModelMap modelMap){
//添加字符串
modelMap.addAttribute("a","A");
modelMap.addAttribute("b","B");
//添加map对象
Map<String,Object> data = new HashMap<String,Object>();
data.put("msg", "hello");
modelMap.addAttribute("data", data);
return "index";
}
}
- 测试页面:/templates/fm/index.ftl
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<p>${a}</p>
<p>${b}</p>
<p>${data.msg}</p>
</body>
</html>