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/

)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章