SpringBoot 集成 Jsp、Thymeleaf 模板 + Thymeleaf 基本使用

SpringBoot 知識點目錄: SpringBoot 2020 核心知識點整理!

集成 Jsp 模板

引入依賴 + 配置文件

引入 jsp 的集成 jar包:

<dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
</dependency>

引入 jsp 運行插件:

<build>
    <finalName>springboot_day1</finalName>
    <!--引入jsp運行插件-->
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

配置文件 中 配置 視圖解析器

spring.mvc.view.prefix=/     # / 代表訪問項目中webapp中頁面
spring.mvc.view.suffix=.jsp

啓動項目

  • 第一種方式:使用插件啓動
    在這裏插入圖片描述
  • 第二種方式:使用 idea 中指定工作目錄啓動[推薦]
    在這裏插入圖片描述
    在這裏插入圖片描述
    通過 http://localhost:8080/index.jsp 可以訪問到 默認 的 index.jsp 界面。

控制器訪問 jsp 頁面

創建一個 /webapp/back/index.jsp 頁面:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page contentType="text/html; UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
<html>
<body>
<h2>this is Back Directory Hello World!</h2>

<h1>獲取項目名字: ${requestScope.name}   ${name}</h1>

<c:forEach items="${requestScope.users}" var="user">
    ID: ${user.id}<br> NAME: ${user.name} <br> AGE: ${user.age} <br> BIR: ${user.bir}
    <br> --------------------------------------------- <br>
</c:forEach>

配置文件中通過 server.servlet.jsp.init-parameters.developmetn=true 開啓熱部署了
</body>
</html>

寫一個控制器:

@Controller // 注意區別, 這裏不用 @RestController
@RequestMapping("user")
public class UserController {
    @GetMapping("findAll")
    public String findAll(HttpServletRequest request, Model model) {
        System.out.println("查詢所有");
        model.addAttribute("name", "zhenyu");
        List<User> users = new ArrayList<>(Arrays.asList(
                new User("1", "zhenyu", 20, new Date()),
                new User("2", "chenchen", 23, new Date())));
        model.addAttribute("users", users);
        return "back/index"; // 視圖解析器: 前綴+邏輯名+後綴 = /back/index
        // return "index"; 視圖解析器: 前綴+邏輯名+後綴 = /index.jsp
    }
}

訪問路徑:localhost:8080/user/findAll
在這裏插入圖片描述

集成 Thymeleaf 模板

Thymeleaf 是跟 VelocityFreeMarker 類似的模板引擎,它可以完全替代 JSP,相較與其他的模板引擎相比,Thymeleaf 在有網絡和無網絡的環境下皆可運行,即它可以讓美工在瀏覽器查看頁面的靜態效果,也可以讓程序員在服務器查看帶數據的動態頁面效果。(jsp 必須運行服務器才能訪問)

引入依賴 + 配置文件

<!--使用thymelaf-->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

配置文件:

# 使用模板目錄
spring.thymeleaf.prefix=classpath:/templates/
# 使用模板後綴
spring.thymeleaf.suffix=.html
# 使用模板編碼
spring.thymeleaf.encoding=UTF-8
# 使用模板響應類型
spring.thymeleaf.servlet.content-type=text/html

# 默認無法直接訪問templates下的頁面, 需要設置
# 以後static下放css與js, templates下放頁面
spring.resources.static-locations=classpath:/templates, classpath:/static

引入下面的依賴是爲了可以直接訪問 html 頁面:

spring.resources.static-locations=classpath:/templates, classpath:/static

例如 不經過控制器 訪問 resources/templates/hello.html:如果不配置上面則無法訪問。

http://localhost:8080/index.html

控制器訪問 html 頁面

使用 Thymeleaf 模板頁面 默認放在 resources/templates 目錄中

創建一個 /resources/templates/hello.html 頁面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>hello</title>
</head>
<body>

SpringBoot 集成 Thymeleaf!!!

</body>
</html>

編寫控制器:

@Controller
@RequestMapping("/hello")
public class HelloController {
    @GetMapping("/hello")
    public String hello() {
        System.out.println("hello spring boot!");
        return "hello";
    }
}

測試訪問:

http://localhost:8080/hello/hello

在這裏插入圖片描述

Thymeleaf 基本使用

在頁面中使用 Thymeleaf 時必須加入以下命名空間:

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

展示單個數據 th:text、th:utext、th:value

控制器中設置數據:

// 控制器中設置數據
model.addAttribute("name", "振宇"); // 或者 request.setAttribute("name", "振宇");
model.addAttribute("username", "<a href=‘’>yusael</a>");
  • 頁面中獲取原樣數據:
<!-- 頁面中獲取數據 -->
<span th:text="${name}"/> 
  • 獲取並解析含有 html 標籤 的數據:
<span th:utext="${username}"></span>
  • 將數據賦值給表單元素:
<!-- 將數據賦值給表單元素 -->
<input type="text" th:value="${name}"/>

總結:

  1. 使用 th:text="${屬性名}" 獲取對應數據,獲取數據時會將對應標籤中數據清空;
  2. 使用 th:utext="${屬性名}" 獲取對應的數據,可以將數據中 html 先解析再渲染到頁面;
  3. 使用 th:value="${屬性名}" 獲取數據直接作爲表單元素 value 屬性

展示對象數據

// 控制器中設置數據
model.addAttribute("user",  new User("1", "振宇", 21, new Date()));
id:	 <span th:text="${user.id}"></span>
name:<span th:text="${user.name}"></span>
age: <span th:text="${user.age}"></span>
bir: <span th:text="${user.bir}"></span>  ====日期格式化  
	 <span th:text="${#dates.format(user.bir, 'yyyy-MM-dd HH:mm')}"></span>

條件展示數據 th:if、運算符

// 控制器中設置數據
model.addAttribute("user",  new User("1", "振宇", 21, new Date()));
<span th:if="${user.age} eq 23">青年</span>
<!--年齡小於等於23纔會展示名字-->
<span th:if="${user.age} le 23" th:text="${user.name}"></span>

運算符:

  • gt : great than >
  • ge : great equal >=
  • eq : equal ==
  • lt : less than <
  • le : less equal <=
  • ne : not equal !=

展示多條數據 th:each

// 控制器中設置數據
List<User> users = Arrays.asList(
	new User("2", "張三", 23,  new Date()),
	new User("3", "李四", 24, new Date())
);
model.addAttribute("users", users);
  • 直接遍歷集合:
<ul th:each="user : ${users}">
	<li th:text="${user.id}"/>
	<li th:text="${user.name}"/>
	<li th:text="${user.age}"/>
	<li th:text="${#dates.format(user.bir, 'yyyy年MM月dd日')}"/>
</ul>
  • 遍歷時獲取遍歷狀態:
<ul th:each="user, userStat : ${users}">
	<li>當前遍歷的次數:<span th:text="${userStat.count}"/>
		當前遍歷的索引:<span th:text="${userStat.index}"/>
		當前遍歷是否是奇數行:<span th:text="${userStat.odd}"/>
		當前遍歷是否是偶數行:<span th:text="${userStat.even}"/>
	</li>
</ul>

引入靜態資源

使用 Thymeleaf 模板項目中 靜態資源 默認放在 resources/static 目錄中

項目中放入對應靜態資源:
在這裏插入圖片描述
頁面中引入:通過 @{/xxx} 去獲取 resources/static 路徑

<link rel="stylesheet" th:href="@{/css/index.css}">
<script th:src="@{/js/jquery-3.5.0.min.js}"></script>

綜合案例

User:

@Data
@AllArgsConstructor
@ToString
public class User {
    private String id;
    private String name;
    private Integer age;
    private Date bir;
}

UserController:

@Controller
@RequestMapping("user")
public class UserController {
    @GetMapping("findAll")
    public String findAll(HttpServletRequest request, Model model) {
        System.out.println("查詢所有");
        model.addAttribute("name", "振宇");
        model.addAttribute("username", "<a href=‘’>yusael</a>");
        model.addAttribute("user", new User("1", "小三", 23, new Date()));
        List<User> users = Arrays.asList(new User("2", "張三", 23,  new Date()),
                                         new User("3", "李四", 24, new Date()));
        model.addAttribute("users", users);
        return "index"; // 邏輯名
    }

    @GetMapping("delete")
    @ResponseBody // 以json響應給瀏覽器
    public String delete(String id, String name) {
        return "刪除id爲:" + id + ", name爲:" + name + "的信息。";
    }
}

resources/templates 目錄下 index.html:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Index</title>
</head>

<body>
    <h1>this is thymeleaf html</h1>

    <h1>展示單個數據</h1>
    歡迎: <span th:text="${name}"/>哈哈<br>
    username: <span th:utext="${username}"></span><br>
    輸入: <input type="text" th:value="${name}"><br>

    <h1>展示對象數據</h1>
    <ul>
        <li>id: <span th:text="${user.id}"/></li>
        <li>name: <span th:text="${user.name}"/></li>
        <li>age: <span th:text="${user.age}"/></li>
        <li>bir: <span th:text="${user.bir}"/> ==== 格式化:
                 <span th:text="${#dates.format(user.bir, 'yyyy-MM-dd')}"/>
        </li>
    </ul>

    <h1>有條件展示數據</h1>
    <!--年齡小於等於23纔會展示-->
    <span th:if="${user.age} le 23" th:text="${user.name}"></span>

    <h1>展示多個數據</h1>
    <ul th:each="user,userStat : ${users}">
        <li>當前遍歷的次數:<span th:text="${userStat.count}"/>
            當前遍歷的索引:<span th:text="${userStat.index}"/>
            當前遍歷是否是奇數行:<span th:text="${userStat.odd}"/>
            當前遍歷是否是偶數行:<span th:text="${userStat.even}"/>
        </li>
        <li th:text="${user.id}"/>
        <li th:text="${user.name}"/>
        <li th:text="${user.age}"/>
        <li th:text="${#dates.format(user.bir, 'yyyy年MM月dd日')}"/>
        <li>集合中的總記錄數: <span th:text="${userStat.size}"/></li>
    </ul>

    <h1>測試鏈接中的路徑</h1>
    <a th:href="@{/user/delete(id=99,name='趙六')}">刪除記錄</a>

</body>
</html>

http://localhost:8080/user/findAll
在這裏插入圖片描述

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