一、Spring Boot集成Freemarker视图
首先引入starter坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
要说明的是内部Spring Boot已经集成了FreeMarker,并提供了内部配置类FreeMarkerAutoConfiguration。
配置类:FreeMarkerProperties
public class FreeMarkerProperties extends AbstractTemplateViewResolverProperties {
//会在resources目录下的templates找页面
public static final String DEFAULT_TEMPLATE_LOADER_PATH = "classpath:/templates/";
//前缀没有
public static final String DEFAULT_PREFIX = "";
//后缀.ftlh
public static final String DEFAULT_SUFFIX = ".ftlh";
}
之后在控制器中写一个方法return到视图界面,其就会自动去找.ftlh后缀的文件。
当然也可以通过设置配置修改FreeMarker
#设置FreeMarker视图配置
spring:
freemarker:
#修改freemarker存放的目录
template-loader-path: classpath:/templates/
#freemarker页面的后缀
suffix: .ftl
#编码格式
charset: UTF-8
接下来就可以集成FreeMarker的页面了:
直接通过EL表达式取值就OK了。
二、Spring Boot集成Thymeleaf视图
与FreeMarker一样,starter坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
配置类:ThymeleafProperties
public class ThymeleafProperties {
//与FreeMarker一样也是有一个templates目录
public static final String DEFAULT_PREFIX = "classpath:/templates/";
//后缀.html
public static final String DEFAULT_SUFFIX = ".html";
}
环境选择配置:
需要注意的是,thymeleaf页面存在缓存,如果不强行刷新页面,你会发现你的东西还是改之前的东西,所以需要配置页面缓存。
spring:
thymeleaf:
prefix: classpath:/html/
#关闭thymeleaf页面缓存
cache: false
然后就是 集成Thymeleaf视图,Thymeleaf返回页面是基于html模板的,里面引入了他自己的命名空间:
<html lang="en" xmlns:th="http://www.thymeleaf.org">
然后通过EL表达式去取值:
<h2 th:text="${msg}">