springboot整合模板引擎之-Thymeleaf

1.什么是 FreeMarker?

Thymeleaf是一款用于渲染XML/XHTML/HTML5内容的模板引擎。类似JSP,Velocity,FreeMaker等, 它也可以轻易的与Spring MVC等Web框架进行集成作为Web应用的模板引擎。与其它模板引擎相比, Thymeleaf最大的特点是能够直接在浏览器中打开并正确显示模板页面,而不需要启动整个Web应用。Thymeleaf的主要目标在于提供一种可被浏览器正确显示的、格式良好的模板创建方式,因此也可以用作静态建模。你可以使用它创建经过验证的XML与HTML模板。使用thymeleaf创建的html模板可以在浏览器里面直接打开(展示静态数据),这有利于前后端分离。

可以看一下官网对其的介绍:Thymeleaf是适用于Web和独立环境的现代服务器端Java模板引擎。Thymeleaf的主要目标是为您的开发工作流程带来优雅的自然模板-HTML可以在浏览器中正确显示,并且可以作为静态原型工作,从而可以在开发团队中加强协作。Thymeleaf拥有用于Spring Framework的模块,与您喜欢的工具的大量集成以及插入您自己的功能的能力,对于现代HTML5 JVM Web开发而言,Thymeleaf是理想的选择-尽管它可以做很多事情。

2.如何在springboot中进行使用呢?

      2.1引入pom.xml依赖

 <!-- thymeleaf 模板启动器 -->
  <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
 </dependency>

      2.2配置文件application.properties中添加配置

############################################################
#
# thymeleaf 模板
#
############################################################
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html
# 关闭缓存
spring.thymeleaf.cache=false

      2.3创建Controller测试类

package com.bw.auto.modules.web;

import com.bw.auto.resource.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ThymeleafTest {
    @Autowired
    private Resource resource;

    @RequestMapping("/thymeleafTest")
    public String index(Model model){
        model.addAttribute("name",resource.getName());
        model.addAttribute("number",resource.getNumber());
        return "thymeleaf";
    }
}

       2.4前端显示页面创建(html的创建)

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title></title>
</head>
<body>
Thymeleaf模板引擎
<h1 th:text="${name}"></h1>
<h1 th:text="${number}"></h1>
</body>
</html>

至此整个项目就算完成了,我们看一下项目的工程结构,并且启动一下看看效果!

启动后输入地址:http://localhost:8080/thymeleafTest

这里多说两句,关于Thymeleaf的表达式如何使用,可以去官网查看规则,有兴趣的可以去看看!https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#link-urls

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值