动力节点首页 全国咨询热线:400-8080-105

绑定手机号,登录
手机号

验证码

微信登录
手机号登录
手机号

验证码

微信登录与注册
微信扫码登录与注册

扫码关注微信公众号完成登录与注册
手机号登录
首页 > 文章

SpringBoot 使用 thymeleaf

05-10 17:21 700浏览
举报 T字号
  • 大字
  • 中字
  • 小字

thymeleaf是一款用于渲染XML/XHTML/HTML5内容的模板引擎。类似JSP,Velocity,FreeMaker等, 它也可以轻易的与Spring MVC等Web框架进行集成作为Web应用的模板引擎。与其它模板引擎相比, Thymeleaf最大的特点是能够直接在浏览器中打开并正确显示模板页面,而不需要启动整个Web应用。那么在SpringBoot 框架中如何使用 thymeleaf呢?

首先,我们需要在SpringBoot 框架中引入thymeleaf。

pom文件中添加依赖

        <!--引入thymeleaf模块引擎-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

查看SpringBoot自动配置源码

@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {
 private static final Charset DEFAULT_ENCODING = Charset.forName("UTF-8");
 private static final MimeType DEFAULT_CONTENT_TYPE = MimeType.valueOf("text/html");
 public static final String DEFAULT_PREFIX = "classpath:/templates/";
 public static final String DEFAULT_SUFFIX = ".html";

只要我们把HTML页面放在classpath:/templates/,thymeleaf就能自动渲染

1.导入thymeleaf的名称空间

在HTML文件的标签中添加属性:xmlns:th="http://www.thymeleaf.org"

<html lang="en" xmlns:th="http://www.thymeleaf.org">

2.编写Controller跳转到页面

    /**
     * @return 跳转到classpath:/templates/success.html
     */
    @RequestMapping("/success")
    public String success(Map<String,Object> map){
        map.put("who","moti");
        return "success";
    }

3.编写html文件

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <!--th:text 将div里面的文本内容设置为 -->
    <h1>欢迎你,<span th:text="${who}"></span>!</h1>
</body>
</html>

以上就是SpringBoot 使用 thymeleaf的具体步骤,这些详细的步骤及源码都是源自动力节点在线的视频课程,动力节点在线专注Java学习,是一家Java在线免费学习网站,你值得拥有!

0人推荐
共同学习,写下你的评论
0条评论
代码小兵652
程序员代码小兵652

113篇文章贡献392215字

相关课程 更多>

作者相关文章更多>

推荐相关文章更多>

JavaWeb的3大组件

代码小兵49806-11 15:28

全面解析Cookie技术

代码小兵49806-11 15:51

浅谈JavaWeb架构演变

代码小兵49806-11 16:22

探讨Web开发中的Session存储与管理

代码小兵51603-29 17:28

JavaScript基础知识

 暴风城-小飞04-06 20:49

发评论

举报

0/150

取消