Spring Boot集成Freemarker和Thymeleaf视图

一、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}">
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值