1 模板引擎
在动态 HTML 实现上 Spring Boot 依然可以完美胜任,并且提供了多种模板引擎的默认配置支持,所以在推荐的模板引擎下,我们可以很快的上手开发动态网站。
Spring Boot
提供了默认配置的模板引擎主要有以下几种:
Thymeleaf
FreeMarker
Velocity
Groovy
Mustache
Spring Boot
建议使用这些模板引擎,避免使用 JSP
,若一定要使用 JSP
将无法实现 Spring Boot 的多种特性,具体可见后文:支持 JSP 的配置
当你使用上述模板引擎中的任何一个,它们默认的模板配置路径为: src/main/resources/templates
。当然也可以修改这个路径,具体如何修改,可在后续各模板引擎的配置属性中查询并修改。
2 在 pom.xml
中引入 freemarker
<!-- 引入freeMarker的依赖包. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
3 关闭 freemarker
缓存
# freemarker配置
spring:
freemarker:
allow-request-override: false
cache: true
check-template-location: true
charset: utf-8
content-type: text/html
expose-request-attributes: false
expose-session-attributes: false
expose-spring-macro-helpers: false
suffix: .ftl
template-loader-path: classpath:/templates/
4 编写模板文件 hello.ftl
,放到 resources/templates
下面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>
Hello freemarker !
<br>
My name is <span>${name}</span>!
</h1>
</body>
</html>
5 编写访问文件的 HelloController
package com.snow.snow_springboot;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Map;
/**
*
* 第一个Controller测试类
*
* @author: yang
* @Date:
* @Description:
* @version v1.0
*/
@Controller
@RequestMapping("/templates")
public class HelloController {
@RequestMapping("/hello")
public String sayHello(Map<String,Object> map){
map.put("name", "Nancy");
return "hello";
}
}
浏览器请求 http://localhost:8080/templates/hello
会找到相应的 servlet,返回 hello,找到 resources/templates/hello.ftl
,返回页面。
测试:能成功取值。