springboot 整合 thymeleaf

引言

springboot 整合thymeleaf 其实用的不是很多,因为现在很多公司都是前后端分离的项目,通过接口交互了。但是我们后端人员,对前端不是很了解,但是又想做些东西看看效果。所以就可以整合 thymeleaf ,掌握一些基本的语法,就可以很好的操作啦。

使用

首先引入依赖,这样我们在项目中才能使用到。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

在html 文件中想要使用 ,需要引入

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

接下来就可以使用啦。

在用之前我们先来看看这些基础语法。

标签

标准表达式

变量表达式:${…}

主要获取上下文的参数变量

<p th:text="${title}">默认值</p>

同时,Thymeleaf 提供了内置对象

 # ctx:上下文对象
 # vars:上下文变量
 # locale:上下文区域设置
 # request:HttpServletRequest 对象
 # response:HttpServletResponse对象
 # session:HttpSession对象
 # servletContext:ServletContext 对象

eg:

The locale country is: <span th:text="${#locale.country}">US</span>.

选择变量表达式:*{…}

一般从被选定的对象中获取属性值

<div th:object="${book}">
 <p>titile: <span th:text="*{title}">ຽ᷌</span>.</p>
</div>

消息表达式#{…}

消息表达式主要用于Thymeleaf 模版页面国际化内容的动态替换和展示板。

链接表达式@{…}

一般用于页面的跳转或者资源的引入。

<a th:href="@{http://localhost:8080/order/details(orderId=${o.id})}">view</a> <a th:href="@{/order/details(orderId=${o.id})}">view</a>

严格按照:

@{路径(参数名=参数值,参数名=参数值…)}的形式编写

片段表达式~{…}

用来标记一个片段模版并且根据需要移动或者传递给其他模版

<div th:insert="~{thymeleafDemo::title}"></div>

这里有一个login.html 的页面,就是整合了thymeleaf

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1,shrink-to-fit=no">
    <title>用户登录界面</title>
    <link th:href="@{/login/css/bootstrap.min.css}" rel="stylesheet">
    <link th:href="@{/login/css/signin.css}" rel="stylesheet">
</head>
<body class="text-center">
<!--  用户登录form表单 -->
<form class="form-signin">
    <img class="mb-4" th:src="@{/login/img/login.jpg}" width="72" height="72">
    <h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">请登录</h1>
    <input type="text" class="form-control"
           th:placeholder="#{login.username}" required="" autofocus="">
    <input type="password" class="form-control"
           th:placeholder="#{login.password}" required="">
    <div class="checkbox mb-3">
        <label>
            <input type="checkbox" value="remember-me"> [[#{login.rememberme}]]
        </label>
    </div>
    <button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.button}">登录</button>
    <p class="mt-5 mb-3 text-muted">© <span th:text="${currentYear}">2019</span>-<span th:text="${currentYear}+1">2020</span></p>
    <a class="btn btn-sm" th:href="@{/toLoginPage(l='zh_CN')}">中文</a>
    <a class="btn btn-sm" th:href="@{/toLoginPage(l='en_US')}">English</a>

</form>
</body>
</html>

最终显示的效果如下:

搭建个人博客界面

下面我们就搭建一个demo 吧,整合mybatis ,将文章列表显示在界面上,实现整合pageHelper 实现分页效果。在界面上显示上一页下一页。

1、创建表。sql 如下:

create DATABASE blog_system
DROP TABLE IF EXISTS t_article;
CREATE TABLE t_article (
  id int(11) NOT NULL AUTO_INCREMENT,
  title varchar(50) NOT NULL COMMENT '文章标题',
  content longtext COMMENT '文章具体内容',
  created date NOT NULL COMMENT '发表时间',
  modified date DEFAULT NULL COMMENT '修改时间',
  categories varchar(200) DEFAULT '默认分类' COMMENT '文章分类',
  tags varchar(200) DEFAULT NULL COMMENT '文章标签',
  allow_comment tinyint(1) NOT NULL DEFAULT '1' COMMENT '是否允许评论',
  thumbnail varchar(200) DEFAULT NULL COMMENT '文章缩略图',
  PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of t_article
-- ----------------------------
INSERT INTO t_article VALUES ('1', '2019新版Java学习路线图','Java学习路线图具体内容具体内容具体内容具体内容具体内容具体内容具体内容','2019-10-10', null, '默认分类', '‘2019,Java,学习路线图', '1', null);
INSERT INTO t_article VALUES ('2', '2019新版Python学习线路图','据悉,Python已经入驻小学生教材,未来不学Python不仅知识会脱节,可能与小朋友都没有了共同话题~~所以,从今天起不要再找借口,不要再说想学Python却没有资源,赶快行动起来,Python等你来探索' ,'2019-10-10', null, '默认分类', '‘2019,Java,学习路线图', '1', null);
INSERT INTO t_article VALUES ('3', 'JDK 8——Lambda表达式介绍',' Lambda表达式是JDK 8中一个重要的新特性,它使用一个清晰简洁的表达式来表达一个接口,同时Lambda表达式也简化了对集合以及数组数据的遍历、过滤和提取等操作。下面,本篇文章就对Lambda表达式进行简要介绍,并进行演示说明' ,'2019-10-10', null, '默认分类', '‘2019,Java,学习路线图', '1', null);
INSERT INTO t_article VALUES ('4', '函数式接口','虽然Lambda表达式可以实现匿名内部类的功能,但在使用时却有一个局限,即接口中有且只有一个抽象方法时才能使用Lamdba表达式代替匿名内部类。这是因为Lamdba表达式是基于函数式接口实现的,所谓函数式接口是指有且仅有一个抽象方法的接口,Lambda表达式就是Java中函数式编程的体现,只有确保接口中有且仅有一个抽象方法,Lambda表达式才能顺利地推导出所实现的这个接口中的方法' ,'2019-10-10', null, '默认分类', '‘2019,Java,学习路线图', '1', null);
INSERT INTO t_article VALUES ('5', '虚拟化容器技术——Docker运行机制介绍','Docker是一个开源的应用容器引擎,它基于go语言开发,并遵从Apache2.0开源协议。使用Docker可以让开发者封装他们的应用以及依赖包到一个可移植的容器中,然后发布到任意的Linux机器上,也可以实现虚拟化。Docker容器完全使用沙箱机制,相互之间不会有任何接口,这保证了容器之间的安全性' ,'2019-10-10', null, '默认分类', '‘2019,Java,学习路线图', '1', null);

2、创建springboot 项目,引入依赖如下:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
	<version>2.1.3</version>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <exclusions>
        <exclusion>
        <groupId>org.junit.vintage</groupId>
        <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<!--分页助手-->
<!--导入pagehelper相关依赖-->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.1.2</version>
</dependency>
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-autoconfigure</artifactId>
    <version>1.2.3</version>
</dependency>
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.2.3</version>
</dependency>

3、创建实体类。

public class Article {

    private Integer id;
    private String title;
    private String content;
    private Date created;
    private Date modified;
    private String categories;
    private String tags;
    private Integer allowComment;
    private String thumbnail;
    getter()/setter()
}

5、创建mapper 接口

@Mapper
public interface ArticleMapper {

    List<Article> selectList();
}

6、创建mapper 对应的xml 文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="cn.quellanan.springboothomework.mapper.ArticleMapper">

    <select id="selectList" resultType="article">
        select * from tb_article
    </select>
</mapper>

7、创建service 以及实现类。使用 PageHelper 实现分页

public interface ArticleService {
    List<Article> selectList(int index,int size);
}


@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;


    @Override
    public List<Article> selectList(int index,int size) {
        PageHelper.startPage(index,size);
        List<Article> articles = articleMapper.selectList();
        return articles;
    }
}

8、创建controller 层接口

@Controller
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @RequestMapping("/")
    public String list(Model model, @RequestParam(required = false)Integer index, @RequestParam(required = false)Integer size){
        if(index==null ||size==null){
            index=1;
            size=2;
        }
        List<Article> articles = articleService.selectList(index,size);
        PageInfo<Article> pageInfo=new PageInfo<>(articles);
        model.addAttribute("articles", articles);
        model.addAttribute("pageInfo", pageInfo);
        return "client/index";
    }
}

9、配置文件中增加配置。

# Mysql数据库连接配置 : com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456

#开启驼峰命名匹配映射mapper
mybatis.configuration.map-underscore-to-camel-case=true

#配置mybatis的xml映射配置文件路径
mybatis.mapper-locations=classpath:mapper/*.xml
#配置mybatis映射配置文件中实体类别名
mybatis.type-aliases-package=cn.quellanan.springboothomework.pojo


# thymeleaf页面缓存设置
spring.thymeleaf.cache=false

# 配置pagehelper参数
pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql

10、引入静态文件资源。

11、编辑index.html 文件。

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<!-- 载入文章头部页面,位置在/client文件夹下的header模板页面,模板名称th:fragment为header -->
<div th:replace="/client/header::header(null,null)" />
<body>
<div class="am-g am-g-fixed blog-fixed index-page">
    <div class="am-u-md-8 am-u-sm-12">


        <!-- 文章遍历并分页展示 : 需要同学们手动完成,基本样式已经给出,请使用th标签及表达式完成页面展示 -->
        <div th:each="article,stat:${articles}" th:value="article">
            <article class="am-g blog-entry-article">

                <div class="am-u-lg-6 am-u-md-12 am-u-sm-12 blog-entry-text">
                    <!-- 文章分类 -->
                    <span class="blog-color"style="font-size: 15px;"><a>默认分类</a></span>
                    <span>&nbsp;&nbsp;&nbsp;</span>
                    <!-- 发布时间 -->
                    <span style="font-size: 15px;" th:text="'发布于 '+ ${article.created}" />
                    <h2>
                        <!-- 文章标题 -->
                        <div><a style="color: #0f9ae0;font-size: 20px;" th:text="${article.title}" />
                        </div>
                    </h2>
                    <!-- 文章内容-->
                    <div style="font-size: 16px;" th:text="${article.content}" />
                </div>
            </article>
        </div>
        <div>
            <a class="btn btn-sm" th:href="@{/(index=1,size=2)}">首页</a>

            <a class="btn btn-sm" th:href="@{/(index=${pageInfo.getPageNum()-1},size=2)}">上一页</a>
            <a class="btn btn-sm" th:href="@{/(index=${pageInfo.getPageNum()}+1,size=2)}">下一页</a>
            <a class="btn btn-sm" th:href="@{/(index=${pageInfo.getPages()},size=2)}">尾页</a>
        </div>




    </div>
    <!-- 博主信息描述 -->
    <div class="am-u-md-4 am-u-sm-12 blog-sidebar">
        <div class="blog-sidebar-widget blog-bor">
            <h2 class="blog-text-center blog-title"><span>子慕</span></h2>
            <img th:src="@{/assets/img/me.jpg}" alt="about me" class="blog-entry-img"/>
            <p>
                Java后台开发
            </p>
            <p>个人博客小站,主要发表关于Java、Spring、Docker等相关文章</p>
        </div>
        <div class="blog-sidebar-widget blog-bor">
            <h2 class="blog-text-center blog-title"><span>联系我</span></h2>
            <p>
                <a><span class="am-icon-github am-icon-fw blog-icon"></span></a>
                <a><span class="am-icon-weibo am-icon-fw blog-icon"></span></a>
            </p>
        </div>
    </div>

</div>
</body>
<!-- 载入文章尾部页面,位置在/client文件夹下的footer模板页面,模板名称th:fragment为footer -->
<div th:replace="/client/footer::footer" />
</html>

12、测试

启动项目,访问

http://localhost:8080/

总结

如果简单使用的话,整合 thymeleaf 还是非常方便的,但是现在主流的项目应该都前后端分离了,不过做全栈的小伙伴还是可以了解的,我们知道有这种技术就可以啦,要用的时候能上手就行

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Boot 可以很方便的集成 Thymeleaf 模板引擎,下面是整合步骤: 1.添加 Thymeleaf 依赖 在 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> ``` 2.配置 Thymeleaf 模板 在 `src/main/resources/templates/` 目录下创建一个 thymeleaf 模板文件,例如 index.html: ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Thymeleaf Demo</title> </head> <body> <h1 th:text="${message}">Hello World!</h1> </body> </html> ``` 其中 `${message}` 表示从后台传递过来的数据。 3.配置视图解析器 在 application.properties 或 application.yml 文件中添加以下配置: ```yaml spring: thymeleaf: cache: false prefix: classpath:/templates/ suffix: .html encoding: utf-8 ``` 其中: - `cache` 表示是否开启缓存 - `prefix` 表示模板文件所在目录 - `suffix` 表示模板文件后缀 - `encoding` 表示模板文件编码 4.在 Controller 中使用 Thymeleaf 在 Controller 中设置需要传递到前端的数据,并指定要返回的模板文件名: ```java @Controller public class DemoController { @GetMapping("/hello") public String hello(Model model) { model.addAttribute("message", "Hello, Thymeleaf!"); return "index"; } } ``` 其中: - `@Controller` 表示这是一个控制器 - `@GetMapping("/hello")` 表示处理 GET 请求,路径为 /hello - `Model` 用于存储需要传递到前端的数据 - `return "index"` 表示返回名为 index 的模板文件 5.运行项目 启动 Spring Boot 项目,访问 http://localhost:8080/hello 即可看到效果。 以上就是 Spring Boot 整合 Thymeleaf 的基本步骤,希望能对你有所帮助。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员爱酸奶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值