SpringBoot中添加Thymeleaf支持以及簡單小案例使用

      SpringBoot通過org.springframework.boot.autoconfigure.thymeleaf包對Thymeleaf進行自動配置。

第一步:在pom.xml文件中添加如下依賴:

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

第二步:在application.properties配置文件中對默認設置進行修改,如下:

# thymeleaf相關配置參數 (ThymeleafAutoConfiguration)
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html

#開發時關閉緩存,不然沒法看到實時頁面
spring.thymeleaf.cache=false

這樣我們就配置完成了,可以在*.html文件中進行使用啦~~

接下來!!!

在SpringBoot中使用Thymeleaf的小案例(通過Controller成功訪問靜態資源和模板頁面

以在瀏覽器中訪問登錄頁面爲例:

1. 靜態資源架構圖:

2. login.html文件如下:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>登錄頁 | Log in</title>
    <!-- Tell the browser to be responsive to screen width -->
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" th:href="@{admin/dist/img/favicon.png}"/>
    <!-- Font Awesome -->
    <link rel="stylesheet" th:href="@{admin/dist/css/font-awesome.min.css}">
    <!-- Ionicons -->
    <link rel="stylesheet" th:href="@{admin/dist/css/ionicons.min.css}">
    <!-- Theme style -->
    <link rel="stylesheet" th:href="@{admin/dist/css/adminlte.min.css}">
    <style>
        canvas {
            display: block;
            vertical-align: bottom;
        }
        #particles {
            background-color: #F7FAFC;
            position: absolute;
            top: 0;
            width: 100%;
            height: 100%;
            z-index: -1;
        }
    </style>
</head>
<body class="hold-transition login-page">
div class="login-box">
   ......
   ......
   ......(登錄頁面具體佈局省略......)
   ......
   ......
</div>
<!-- /.login-box -->

<!-- jQuery -->
<script th:src="@{admin/plugins/jquery/jquery.min.js}"></script>
<!-- Bootstrap 4 -->
<script th:src="@{admin/plugins/bootstrap/js/bootstrap.bundle.min.js}"></script>
</body>
</html>

3. IndexController.java文件如下:(當然,獲取登錄頁面的方式不止作者寫的這一種,網上都可以找到的,本人就不贅述了)

package zqq.trys.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * @Auther: zhangqingqing
 * @Date: 2019/12/24 11:32
 * @Description:
 */
@Controller
public class IndexController{
    /**
     * 登錄頁面
     *
     * @return
     */
    @RequestMapping("/loginPage")
    public ModelAndView getSidebarPage() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("admin/login");
        return modelAndView;
    }

}

 4. 通過網址:http://localhost:8082/loginPage來訪問,效果圖如下:(端口8082是本人在application.properties中配置的,也可以配置爲其它。)

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