Spring Boot整合模板引擎freemarker
jsp本质是servlet,渲染都在服务器,freemarker模板引擎也是在服务器端渲染。
项目结构
引入依赖pom.xml
<!-- 引入 freemarker 模板依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
配置application.properties
############################################################
#
# freemarker 静态资源配置
#
############################################################
#设定ftl文件路径
spring.freemarker.template-loader-path=classpath:/templates
# 关闭缓存, 即时刷新, 上线生产环境需要改为true
spring.freemarker.cache=false
spring.freemarker.charset=UTF-8
spring.freemarker.check-template-location=true
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=true
spring.freemarker.expose-session-attributes=true
spring.freemarker.request-context-attribute=request
spring.freemarker.suffix=.ftl
模板页index.html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8" />
<title></title>
</head>
<body>
FreeMarker模板引擎
<h1>${resource.name}</h1>
<h1>${resource.website}</h1>
<h1>${resource.language}</h1>
</body>
</html>
控制器Controller
@Controller
@RequestMapping("demo/ftl")
public class FreemarkerController {
@RequestMapping("/index")
public String index(ModelMap map) {
Map<String, Object> resource = new HashMap<>();
resource.put("name", "yysue");
resource.put("website", "https://yysue.com");
resource.put("language", "java");
map.addAttribute("resource", resource);
return "freemarker/index";
}
@RequestMapping("center")
public String center() {
return "freemarker/center/center";
}
}