Loading [MathJax]/jax/output/CommonHTML/config.js
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >springboot 整合 thymeleaf(上手即用)

springboot 整合 thymeleaf(上手即用)

作者头像
用户5546570
发布于 2020-07-08 02:45:34
发布于 2020-07-08 02:45:34
69600
代码可运行
举报
运行总次数:0
代码可运行

引言

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

使用

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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<html lang="en" xmlns:th="http://www.thymeleaf.org">

接下来就可以使用啦。

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

标签
标准表达式
变量表达式:${...}

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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<p th:text="${title}">默认值</p>

同时,Thymeleaf 提供了内置对象

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
 # ctx:上下文对象
 # vars:上下文变量
 # locale:上下文区域设置
 # request:HttpServletRequest 对象
 # response:HttpServletResponse对象
 # session:HttpSession对象
 # servletContext:ServletContext 对象

eg:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
The locale country is: <span th:text="${#locale.country}">US</span>.
选择变量表达式:*{...}

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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<div th:object="${book}">
 <p>titile: <span th:text="*{title}">ຽ᷌</span>.</p>
</div>
消息表达式#{...}

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

链接表达式@{...}

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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<a th:href="@{http://localhost:8080/order/details(orderId=${o.id})}">view</a> <a th:href="@{/order/details(orderId=${o.id})}">view</a>

严格按照:

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

片段表达式~{...}

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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<div th:insert="~{thymeleafDemo::title}"></div>

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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<!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 如下:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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 项目,引入依赖如下:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<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、创建实体类。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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 接口

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
@Mapper
public interface ArticleMapper {

    List<Article> selectList();
}

6、创建mapper 对应的xml 文件

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<?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 实现分页

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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 层接口

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
@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、配置文件中增加配置。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
# 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 文件。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<!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>   </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、测试

启动项目,访问

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
http://localhost:8080/

GitHub地址:https://github.com/abel-max/Java-Study-Note/tree/master 来源:https://www.tuicool.com/articles/YNnaya3

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
[SpringBoot——Web开发(使用Thymeleaf模板引擎)]
https://github.com/HCJ-shadow/SpringBootPlus
Noneplus
2019/09/24
5040
[SpringBoot——Web开发(使用Thymeleaf模板引擎)]
lagou 爪哇 1-4 spring boot 笔记
在开发过程中,通常会对一段业务代码不断地修改测试,在修改之后往往需要重启服务,有些服务需要加载很久才能启动成功,这种不必要的重复操作极大的降低了程序开发效率。为此,Spring Boot框架专门提供了进行热部署的依赖启动器,用于进行项目热部署,而无需手动重启项目
acc8226
2022/05/17
7340
lagou 爪哇 1-4 spring boot 笔记
SpringBoot整合MVC Mybatis plus 最全thymeleaf讲解(保姆级讲解,带Java代码案例讲解)
默认的静态资源路径为: classpath:/META-INF/resources/ 或者 classpath:/resources/ 或者 classpath:/static/ 或者 classpath:/public 或者 只要静态资源放在这些目录中任何一个, SpringMVC 都会帮我们处理。 我们习惯会把静态资源放在 classpath:/static/ 目录下。
编程张无忌
2021/01/26
1.4K0
SpringBoot整合MVC Mybatis plus  最全thymeleaf讲解(保姆级讲解,带Java代码案例讲解)
(带界面)SpringBoot整合PageHelper实现分页
在我们的业务开发中,查询出的数据可能成千上万条,如果将大量数据一次性全部展示给客户,不仅会照成性能问题,也会会造成很不好的用户体验,界面延迟展示、界面过长等问题。而且用户大概率也不会想一次性得到全部的数据,在这种情况下我们就应该使用分页来分批次展示数据了。主流数据库也为我们提供了相应的分页功能,比如mysql的limit。
东边的大西瓜
2022/05/05
8910
(带界面)SpringBoot整合PageHelper实现分页
Spring Boot 入门
约定优于配置(Convention over Configuration),又称按约定编程,是一种软件设计范式。
RendaZhang
2020/11/11
2.4K0
Spring Boot 入门
Thymeleaf【快速入门】Thymeleaf介绍
然后官网还给出了一段看起来仍然像HTML一样工作的集成了Thymeleaf模版的代码,我们大致的来感受一下:
我没有三颗心脏
2019/01/03
4.1K0
杨校老师课堂之就业信息平台
1. 创建maven项目 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.
杨校
2021/05/13
9760
SSM整合案例
解释jdbcUrl后面的参数useUnicode Mysql jdbc URL连接参数useSSL、serverTimezone 相关问题
大忽悠爱学习
2021/11/15
4.7K0
springboot 整合 Mybatis、JPA、Redis「建议收藏」
在springboot 项目中,我们是用ORM 框架来操作数据库变的非常方便。下面我们分别整合mysql ,spring data jpa 以及redis 。让我们感受下快车道。
全栈程序员站长
2022/11/01
7140
springboot 整合 Mybatis、JPA、Redis「建议收藏」
Spring Boot 2.X(三):使用 Spring MVC + MyBatis + Thymeleaf 开发 web 应用
Spring MVC 是构建在 Servlet API 上的原生框架,并从一开始就包含在 Spring 框架中。本文主要通过简述 Spring MVC 的架构及分析,并用 Spring Boot + Spring MVC + MyBatis (SSM)+ Thymeleaf(模板引擎) 框架来简单快速构建一个 Web 项目。
朝雾轻寒
2019/10/18
1.5K1
Spring Boot 2.X(三):使用 Spring MVC + MyBatis + Thymeleaf 开发 web 应用
SpringBoot引入Thymeleaf
许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。
Bobby
2019/04/09
1.8K0
SpringBoot引入Thymeleaf
SpringBoot 实战 (十二) | 整合 thymeleaf
如题,今天介绍 Thymeleaf ,并整合 Thymeleaf 开发一个简陋版的学生信息管理系统。
JavaFish
2019/10/17
1.1K0
SpringBoot 实战 (十二) | 整合 thymeleaf
使用idea实现springboot Mybatis 整合(springboot 2.x)
本来这篇博文老在就写好了,但是后来发现很多功能其实根本就没有检验通过就发出来了,导致遗留了很多坑,比如最难搞的就是SqlSessionFactory和PageHelper,之前写过关于springboot1.5.6版本的整合,这段时间刚好springboot发布了2.0的正式版本,很多同学可能没有注意版本,导致了整合的时候出现了很多很多的问题,这几天刚好有空就试着整合一下springboot2.0 mybatis,发现了很多很多的坑,而且网上的资源也不多,终于在两天的踩坑中成功整合了,并且将翻页功能修复好了,废话不多说了,看代码:
凯哥Java
2019/06/30
1.5K0
SSM整合
Spring提供了监听器ContextLoaderListener,实现ServletContextListener接口,可监听
捞月亮的小北
2023/12/01
2440
SpringBoot整合常用技术
​ Spring Boot是目前大火的Java后端框架,遵循着“约定大于配置”的规则,可以快速开发后台,摆脱SSM框架的各种xml配置,开箱即用,快速部署。依靠着spring的强大社区,框架中集成了各种优秀的第三方框架。
MiChong
2020/09/24
4430
SpringBoot综合案例
前面介绍了Freemaker,这节介绍SpringBoot整合MyBatis,同时结合Freemaker展现数据
Java鱼头
2022/12/01
5921
Spring学习笔记(十九)——springboot Web开发和模板引擎thymeleaf语法使用
2)、SpringBoot已经默认将这些场景配置好了,只需要在配置文件中指定少量配置就可以运行起来
不愿意做鱼的小鲸鱼
2022/09/26
9150
Spring学习笔记(十九)——springboot Web开发和模板引擎thymeleaf语法使用
SpringBoot整合ThymeLeaf
大家好,我是 Leo,今天我们来学习 Thymeleaf,如果你对 Thymeleaf 比较陌生也不要紧,它很容易学习与理解,并有着自己鲜明的特色。
程序员Leo
2023/08/11
8491
SpringBoot整合ThymeLeaf
springboot学习笔记-thymeleaf
简单说, Thymeleaf 是一个跟 Velocity、FreeMarker 类似的模板引擎,它可以完全替代 JSP 。相较与其他的模板引擎,它有如下三个极吸引人的特点:
Janti
2018/08/01
9150
SpringBoot与PageHelper的整合示例详解
SpringBoot与PageHelper的整合示例详解 1.PageHelper简介 PageHelper官网地址: https://pagehelper.github.io/ 摘要: com.github.pagehelper.PageHelper是一款好用的开源免费的Mybatis第三方物理分页插件。 PageHelper是一款好用的开源免费的Mybatis第三方物理分页插件,其实我并不想加上好用两个字,但是为了表扬插件作者开源免费的崇高精神,我毫不犹豫的加上了好用一词作为赞美。 原本以为分
Dream城堡
2019/07/22
3.6K0
相关推荐
[SpringBoot——Web开发(使用Thymeleaf模板引擎)]
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档