一、freemarker
SpringBoot内部支持Freemarker视图技术的集成,并提供了自动化配置类FreeMarkerAutoConfiguration,借助自动化配置可以很方便的集成Freemarker基础到 SpringBoot环境中。
1.引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
2.查找配置类
在idea上双击shift搜索FreeMarkerProperties
,
可以看到,freemareker默认加载路径是类路径下一个叫templates
的文件夹,并且后缀默认为.ftlh
。
3.更换配置
如果我们不想用springboot的默认配置,那么可以在application.yml文件中修改这些配置。
spring:
freemarker:
#加载路径
template-loader-path: classpath:/view/
##后缀
suffix: .ftl
##字符
charset: UTF-8
4.访问视图
在resources目录下新建目录views,同时新建一个以后缀.ftl
结尾的文件:
<h1>牛马</h1>
<h2>${msg}</h2>
在controller层编写方法,访问视图:
@RequestMapping("index")
public String index(Model model) {
model.addAttribute("msg", "hello springboot");
return "index";
}
浏览器输入http://localhost:8080/index
,看到如下页面:
二、thymeleaf
1.引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.查找配置类
在idea上双击shift搜索ThymeleafProperties
,
可以看到,thymeleaf默认加载路径是类路径下一个叫templates
的文件夹,并且后缀默认为.html
。
3.更换配置
如果我们不想用springboot的默认配置,那么可以在application.yml文件中修改这些配置。
spring:
thymeleaf:
# 加载路径
prefix: classpath:/views/
suffix: .html
4.访问视图
在resources目录下新建目录views,同时新建一个以后缀.html
结尾的文件:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1 th:text="${msg}"></h1>
</body>
</html>
在controller层编写方法,访问视图:
@RequestMapping("index")
public String index(Model model) {
model.addAttribute("msg", "hello springboot");
return "index";
}
浏览器输入http://localhost:8080/index
,看到如下页面: