最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Spring Boot 視圖層與模板引擎的應(yīng)用方法

 更新時(shí)間:2026年03月04日 15:32:19   作者:星辰徐哥  
SpringBoot視圖層與模板引擎學(xué)習(xí)重點(diǎn)包括基本方法、Thymeleaf、Freemarker和Velocity集成、靜態(tài)資源管理及實(shí)際應(yīng)用場(chǎng)景,本文介紹Spring Boot視圖層與模板引擎,感興趣的朋友跟隨小編一起看看吧

Spring Boot 視圖層與模板引擎

19.1 學(xué)習(xí)目標(biāo)與重點(diǎn)提示

學(xué)習(xí)目標(biāo):掌握Spring Boot視圖層與模板引擎的核心概念與使用方法,包括Spring Boot視圖層的基本方法、Spring Boot與Thymeleaf的集成、Spring Boot與Freemarker的集成、Spring Boot與Velocity的集成、Spring Boot的靜態(tài)資源管理、Spring Boot的實(shí)際應(yīng)用場(chǎng)景,學(xué)會(huì)在實(shí)際開(kāi)發(fā)中處理視圖層問(wèn)題。
重點(diǎn):Spring Boot視圖層的基本方法Spring Boot與Thymeleaf的集成、Spring Boot與Freemarker的集成Spring Boot與Velocity的集成Spring Boot的靜態(tài)資源管理、Spring Boot的實(shí)際應(yīng)用場(chǎng)景。

19.2 Spring Boot視圖層概述

Spring Boot視圖層是指使用Spring Boot進(jìn)行Web應(yīng)用開(kāi)發(fā)的方法。

19.2.1 視圖層的定義

定義:視圖層是指使用Spring Boot進(jìn)行Web應(yīng)用開(kāi)發(fā)的方法。
作用

  • 實(shí)現(xiàn)Web頁(yè)面的渲染。
  • 實(shí)現(xiàn)數(shù)據(jù)的展示。
  • 實(shí)現(xiàn)用戶交互。

? 結(jié)論:視圖層是指使用Spring Boot進(jìn)行Web應(yīng)用開(kāi)發(fā)的方法,作用是實(shí)現(xiàn)Web頁(yè)面的渲染、數(shù)據(jù)的展示、用戶交互。

19.2.2 視圖層的常用組件

定義:視圖層的常用組件是指Spring Boot提供的視圖層組件。
組件

  • Thymeleaf:用于Thymeleaf模板。
  • Freemarker:用于Freemarker模板。
  • Velocity:用于Velocity模板。

? 結(jié)論:視圖層的常用組件包括Thymeleaf、Freemarker、Velocity。

19.3 Spring Boot與Thymeleaf的集成

Spring Boot與Thymeleaf的集成是最常用的視圖層方法之一。

19.3.1 集成Thymeleaf的步驟

定義:集成Thymeleaf的步驟是指使用Spring Boot與Thymeleaf集成的方法。
步驟

  1. 在pom.xml文件中添加Thymeleaf依賴。
  2. 在application.properties或application.yml文件中配置Thymeleaf。
  3. 創(chuàng)建實(shí)體類(lèi)。
  4. 創(chuàng)建Repository接口。
  5. 創(chuàng)建控制器類(lèi)。
  6. 創(chuàng)建Thymeleaf模板文件。
  7. 測(cè)試應(yīng)用。

示例
pom.xml文件中的Thymeleaf依賴:

<dependencies>
    <!-- Web依賴 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- Thymeleaf依賴 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <!-- Data JPA依賴 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <!-- H2數(shù)據(jù)庫(kù)依賴 -->
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
    <!-- 測(cè)試依賴 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

application.properties文件中的Thymeleaf配置:

# 服務(wù)器端口
server.port=8080
# 數(shù)據(jù)庫(kù)連接信息
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
# JPA配置
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
# H2數(shù)據(jù)庫(kù)控制臺(tái)
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
# Thymeleaf配置
spring.thymeleaf.cache=false
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

實(shí)體類(lèi):

import javax.persistence.*;
@Entity
@Table(name = "product")
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String productId;
    private String productName;
    private double price;
    private int sales;
    public Product() {
    }
    public Product(String productId, String productName, double price, int sales) {
        this.productId = productId;
        this.productName = productName;
        this.price = price;
        this.sales = sales;
    }
    // Getter和Setter方法
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getProductId() {
        return productId;
    }
    public void setProductId(String productId) {
        this.productId = productId;
    }
    public String getProductName() {
        return productName;
    }
    public void setProductName(String productName) {
        this.productName = productName;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    public int getSales() {
        return sales;
    }
    public void setSales(int sales) {
        this.sales = sales;
    }
    @Override
    public String toString() {
        return "Product{" +
                "id=" + id +
                ", productId='" + productId + '\'' +
                ", productName='" + productName + '\'' +
                ", price=" + price +
                ", sales=" + sales +
                '}';
    }
}

Repository接口:

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
    List<Product> findBySalesGreaterThan(int sales);
}

控制器類(lèi):

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Controller
@RequestMapping("/products")
public class ProductController {
    @Autowired
    private ProductRepository productRepository;
    @GetMapping("/")
    public String getAllProducts(Model model) {
        List<Product> products = productRepository.findAll();
        model.addAttribute("products", products);
        return "products";
    }
    @PostMapping("/")
    public String addProduct(@ModelAttribute Product product) {
        productRepository.save(product);
        return "redirect:/products/";
    }
    @GetMapping("/top-selling")
    public String getTopSellingProducts(@RequestParam int topN, Model model) {
        List<Product> products = productRepository.findBySalesGreaterThan(0);
        products.sort((p1, p2) -> p2.getSales() - p1.getSales());
        if (products.size() > topN) {
            products = products.subList(0, topN);
        }
        model.addAttribute("products", products);
        return "products";
    }
}

Thymeleaf模板文件(src/main/resources/templates/products.html):

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>產(chǎn)品列表</title>
    <style>
        table {
            border-collapse: collapse;
            width: 100%;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
        th {
            background-color: #f2f2f2;
        }
        .add-product {
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <h1>產(chǎn)品列表</h1>
    <div class="add-product">
        <form th:action="@{/products/}" method="post" th:object="${product}">
            <label>產(chǎn)品ID:</label>
            <input type="text" th:field="*{productId}" required>
            <label>產(chǎn)品名稱:</label>
            <input type="text" th:field="*{productName}" required>
            <label>價(jià)格:</label>
            <input type="number" th:field="*{price}" step="0.01" required>
            <label>銷(xiāo)量:</label>
            <input type="number" th:field="*{sales}" required>
            <button type="submit">添加產(chǎn)品</button>
        </form>
    </div>
    <div>
        <form th:action="@{/products/top-selling}" method="get">
            <label>銷(xiāo)量TOP:</label>
            <input type="number" name="topN" value="3" min="1" required>
            <button type="submit">查詢</button>
        </form>
    </div>
    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>產(chǎn)品ID</th>
                <th>產(chǎn)品名稱</th>
                <th>價(jià)格</th>
                <th>銷(xiāo)量</th>
            </tr>
        </thead>
        <tbody>
            <tr th:each="product : ${products}">
                <td th:text="${product.id}"></td>
                <td th:text="${product.productId}"></td>
                <td th:text="${product.productName}"></td>
                <td th:text="${#numbers.formatDecimal(product.price, 0, 'COMMA', 2, 'POINT')}"></td>
                <td th:text="${product.sales}"></td>
            </tr>
        </tbody>
    </table>
</body>
</html>

測(cè)試類(lèi):

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ProductApplicationTests {
    @LocalServerPort
    private int port;
    @Autowired
    private TestRestTemplate restTemplate;
    @Test
    void contextLoads() {
    }
    @Test
    void testHomePage() {
        String response = restTemplate.getForObject("http://localhost:" + port + "/products/", String.class);
        assertThat(response).contains("產(chǎn)品列表");
    }
}

? 結(jié)論:集成Thymeleaf的步驟包括添加Thymeleaf依賴、配置Thymeleaf、創(chuàng)建實(shí)體類(lèi)、創(chuàng)建Repository接口、創(chuàng)建控制器類(lèi)、創(chuàng)建Thymeleaf模板文件、測(cè)試應(yīng)用。

19.4 Spring Boot與Freemarker的集成

Spring Boot與Freemarker的集成是常用的視圖層方法之一。

19.4.1 集成Freemarker的步驟

定義:集成Freemarker的步驟是指使用Spring Boot與Freemarker集成的方法。
步驟

  1. 在pom.xml文件中添加Freemarker依賴。
  2. 在application.properties或application.yml文件中配置Freemarker。
  3. 創(chuàng)建實(shí)體類(lèi)。
  4. 創(chuàng)建Repository接口。
  5. 創(chuàng)建控制器類(lèi)。
  6. 創(chuàng)建Freemarker模板文件。
  7. 測(cè)試應(yīng)用。

示例
pom.xml文件中的Freemarker依賴:

<dependencies>
    <!-- Web依賴 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- Freemarker依賴 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-freemarker</artifactId>
    </dependency>
    <!-- Data JPA依賴 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <!-- H2數(shù)據(jù)庫(kù)依賴 -->
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
    <!-- 測(cè)試依賴 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

application.properties文件中的Freemarker配置:

# 服務(wù)器端口
server.port=8080
# 數(shù)據(jù)庫(kù)連接信息
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
# JPA配置
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
# H2數(shù)據(jù)庫(kù)控制臺(tái)
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
# Freemarker配置
spring.freemarker.cache=false
spring.freemarker.prefix=classpath:/templates/
spring.freemarker.suffix=.ftl

實(shí)體類(lèi)、Repository接口、控制器類(lèi)與集成Thymeleaf的示例相同。

Freemarker模板文件(src/main/resources/templates/products.ftl):

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>產(chǎn)品列表</title>
    <style>
        table {
            border-collapse: collapse;
            width: 100%;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
        th {
            background-color: #f2f2f2;
        }
        .add-product {
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <h1>產(chǎn)品列表</h1>
    <div class="add-product">
        <form action="/products/" method="post">
            <label>產(chǎn)品ID:</label>
            <input type="text" name="productId" required>
            <label>產(chǎn)品名稱:</label>
            <input type="text" name="productName" required>
            <label>價(jià)格:</label>
            <input type="number" name="price" step="0.01" required>
            <label>銷(xiāo)量:</label>
            <input type="number" name="sales" required>
            <button type="submit">添加產(chǎn)品</button>
        </form>
    </div>
    <div>
        <form action="/products/top-selling" method="get">
            <label>銷(xiāo)量TOP:</label>
            <input type="number" name="topN" value="3" min="1" required>
            <button type="submit">查詢</button>
        </form>
    </div>
    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>產(chǎn)品ID</th>
                <th>產(chǎn)品名稱</th>
                <th>價(jià)格</th>
                <th>銷(xiāo)量</th>
            </tr>
        </thead>
        <tbody>
            <#list products as product>
                <tr>
                    <td>${product.id}</td>
                    <td>${product.productId}</td>
                    <td>${product.productName}</td>
                    <td>${product.price?string(",###.00")}</td>
                    <td>${product.sales}</td>
                </tr>
            </#list>
        </tbody>
    </table>
</body>
</html>

測(cè)試類(lèi):

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ProductApplicationTests {
    @LocalServerPort
    private int port;
    @Autowired
    private TestRestTemplate restTemplate;
    @Test
    void contextLoads() {
    }
    @Test
    void testHomePage() {
        String response = restTemplate.getForObject("http://localhost:" + port + "/products/", String.class);
        assertThat(response).contains("產(chǎn)品列表");
    }
}

? 結(jié)論:集成Freemarker的步驟包括添加Freemarker依賴、配置Freemarker、創(chuàng)建實(shí)體類(lèi)、創(chuàng)建Repository接口、創(chuàng)建控制器類(lèi)、創(chuàng)建Freemarker模板文件、測(cè)試應(yīng)用。

19.5 Spring Boot與Velocity的集成

Spring Boot與Velocity的集成是常用的視圖層方法之一。

19.5.1 集成Velocity的步驟

定義:集成Velocity的步驟是指使用Spring Boot與Velocity集成的方法。
步驟

  1. 在pom.xml文件中添加Velocity依賴。
  2. 在application.properties或application.yml文件中配置Velocity。
  3. 創(chuàng)建實(shí)體類(lèi)。
  4. 創(chuàng)建Repository接口。
  5. 創(chuàng)建控制器類(lèi)。
  6. 創(chuàng)建Velocity模板文件。
  7. 測(cè)試應(yīng)用。

示例
pom.xml文件中的Velocity依賴:

<dependencies>
    <!-- Web依賴 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- Velocity依賴 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-velocity</artifactId>
        <version>1.5.22.RELEASE</version>
    </dependency>
    <!-- Data JPA依賴 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <!-- H2數(shù)據(jù)庫(kù)依賴 -->
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
    <!-- 測(cè)試依賴 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

application.properties文件中的Velocity配置:

# 服務(wù)器端口
server.port=8080
# 數(shù)據(jù)庫(kù)連接信息
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
# JPA配置
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
# H2數(shù)據(jù)庫(kù)控制臺(tái)
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
# Velocity配置
spring.velocity.cache=false
spring.velocity.prefix=classpath:/templates/
spring.velocity.suffix=.vm

實(shí)體類(lèi)、Repository接口、控制器類(lèi)與集成Thymeleaf的示例相同。

Velocity模板文件(src/main/resources/templates/products.vm):

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>產(chǎn)品列表</title>
    <style>
        table {
            border-collapse: collapse;
            width: 100%;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
        th {
            background-color: #f2f2f2;
        }
        .add-product {
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <h1>產(chǎn)品列表</h1>
    <div class="add-product">
        <form action="/products/" method="post">
            <label>產(chǎn)品ID:</label>
            <input type="text" name="productId" required>
            <label>產(chǎn)品名稱:</label>
            <input type="text" name="productName" required>
            <label>價(jià)格:</label>
            <input type="number" name="price" step="0.01" required>
            <label>銷(xiāo)量:</label>
            <input type="number" name="sales" required>
            <button type="submit">添加產(chǎn)品</button>
        </form>
    </div>
    <div>
        <form action="/products/top-selling" method="get">
            <label>銷(xiāo)量TOP:</label>
            <input type="number" name="topN" value="3" min="1" required>
            <button type="submit">查詢</button>
        </form>
    </div>
    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>產(chǎn)品ID</th>
                <th>產(chǎn)品名稱</th>
                <th>價(jià)格</th>
                <th>銷(xiāo)量</th>
            </tr>
        </thead>
        <tbody>
            #foreach ($product in $products)
                <tr>
                    <td>$product.id</td>
                    <td>$product.productId</td>
                    <td>$product.productName</td>
                    <td>$product.price.format("###,###.00")</td>
                    <td>$product.sales</td>
                </tr>
            #end
        </tbody>
    </table>
</body>
</html>

測(cè)試類(lèi):

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ProductApplicationTests {
    @LocalServerPort
    private int port;
    @Autowired
    private TestRestTemplate restTemplate;
    @Test
    void contextLoads() {
    }
    @Test
    void testHomePage() {
        String response = restTemplate.getForObject("http://localhost:" + port + "/products/", String.class);
        assertThat(response).contains("產(chǎn)品列表");
    }
}

? 結(jié)論:集成Velocity的步驟包括添加Velocity依賴、配置Velocity、創(chuàng)建實(shí)體類(lèi)、創(chuàng)建Repository接口、創(chuàng)建控制器類(lèi)、創(chuàng)建Velocity模板文件、測(cè)試應(yīng)用。

19.6 Spring Boot的靜態(tài)資源管理

Spring Boot的靜態(tài)資源管理是視圖層的重要組件。

19.6.1 靜態(tài)資源管理的定義

定義:靜態(tài)資源管理是指使用Spring Boot管理靜態(tài)資源的方法。
作用

  • 管理Web應(yīng)用的靜態(tài)資源,如CSS、JavaScript、圖片等。
  • 提高開(kāi)發(fā)效率。
  • 提供統(tǒng)一的編程模型。

常用靜態(tài)資源目錄

  • src/main/resources/static:用于存放靜態(tài)資源。
  • src/main/resources/public:用于存放靜態(tài)資源。
  • src/main/resources/resources:用于存放靜態(tài)資源。
  • src/main/resources/templates:用于存放模板文件。

示例
創(chuàng)建靜態(tài)資源文件(src/main/resources/static/css/style.css):

body {
    font-family: Arial, sans-serif;
    margin: 0;
    padding: 0;
}
h1 {
    color: #333;
    margin: 20px 0;
}
table {
    border-collapse: collapse;
    width: 100%;
}
th, td {
    border: 1px solid #ddd;
    padding: 8px;
    text-align: left;
}
th {
    background-color: #f2f2f2;
}
.add-product {
    margin-bottom: 20px;
}

在Thymeleaf模板文件中引用靜態(tài)資源:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>產(chǎn)品列表</title>
    <link rel="stylesheet" th:href="@{/css/style.css}" rel="external nofollow" >
</head>
<body>
    <h1>產(chǎn)品列表</h1>
    <div class="add-product">
        <form th:action="@{/products/}" method="post" th:object="${product}">
            <label>產(chǎn)品ID:</label>
            <input type="text" th:field="*{productId}" required>
            <label>產(chǎn)品名稱:</label>
            <input type="text" th:field="*{productName}" required>
            <label>價(jià)格:</label>
            <input type="number" th:field="*{price}" step="0.01" required>
            <label>銷(xiāo)量:</label>
            <input type="number" th:field="*{sales}" required>
            <button type="submit">添加產(chǎn)品</button>
        </form>
    </div>
    <div>
        <form th:action="@{/products/top-selling}" method="get">
            <label>銷(xiāo)量TOP:</label>
            <input type="number" name="topN" value="3" min="1" required>
            <button type="submit">查詢</button>
        </form>
    </div>
    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>產(chǎn)品ID</th>
                <th>產(chǎn)品名稱</th>
                <th>價(jià)格</th>
                <th>銷(xiāo)量</th>
            </tr>
        </thead>
        <tbody>
            <tr th:each="product : ${products}">
                <td th:text="${product.id}"></td>
                <td th:text="${product.productId}"></td>
                <td th:text="${product.productName}"></td>
                <td th:text="${#numbers.formatDecimal(product.price, 0, 'COMMA', 2, 'POINT')}"></td>
                <td th:text="${product.sales}"></td>
            </tr>
        </tbody>
    </table>
</body>
</html>

? 結(jié)論:靜態(tài)資源管理是指使用Spring Boot管理靜態(tài)資源的方法,常用靜態(tài)資源目錄包括src/main/resources/static、src/main/resources/public、src/main/resources/resources、src/main/resources/templates。

19.7 Spring Boot的實(shí)際應(yīng)用場(chǎng)景

在實(shí)際開(kāi)發(fā)中,Spring Boot視圖層與模板引擎的應(yīng)用場(chǎng)景非常廣泛,如:

  • 實(shí)現(xiàn)商品的展示與購(gòu)買(mǎi)。
  • 實(shí)現(xiàn)訂單的管理。
  • 實(shí)現(xiàn)用戶的管理。
  • 實(shí)現(xiàn)博客的發(fā)布與管理。

示例

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.persistence.*;
import java.util.List;
// 產(chǎn)品類(lèi)
@Entity
@Table(name = "product")
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String productId;
    private String productName;
    private double price;
    private int sales;
    public Product() {
    }
    public Product(String productId, String productName, double price, int sales) {
        this.productId = productId;
        this.productName = productName;
        this.price = price;
        this.sales = sales;
    }
    // Getter和Setter方法
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getProductId() {
        return productId;
    }
    public void setProductId(String productId) {
        this.productId = productId;
    }
    public String getProductName() {
        return productName;
    }
    public void setProductName(String productName) {
        this.productName = productName;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    public int getSales() {
        return sales;
    }
    public void setSales(int sales) {
        this.sales = sales;
    }
    @Override
    public String toString() {
        return "Product{" +
                "id=" + id +
                ", productId='" + productId + '\'' +
                ", productName='" + productName + '\'' +
                ", price=" + price +
                ", sales=" + sales +
                '}';
    }
}
// 產(chǎn)品Repository
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
    List<Product> findBySalesGreaterThan(int sales);
}
// 產(chǎn)品控制器
@Controller
@RequestMapping("/products")
public class ProductController {
    @Autowired
    private ProductRepository productRepository;
    @GetMapping("/")
    public String getAllProducts(Model model) {
        List<Product> products = productRepository.findAll();
        model.addAttribute("products", products);
        model.addAttribute("product", new Product());
        return "products";
    }
    @PostMapping("/")
    public String addProduct(@ModelAttribute Product product) {
        productRepository.save(product);
        return "redirect:/products/";
    }
    @GetMapping("/top-selling")
    public String getTopSellingProducts(@RequestParam int topN, Model model) {
        List<Product> products = productRepository.findBySalesGreaterThan(0);
        products.sort((p1, p2) -> p2.getSales() - p1.getSales());
        if (products.size() > topN) {
            products = products.subList(0, topN);
        }
        model.addAttribute("products", products);
        model.addAttribute("product", new Product());
        return "products";
    }
}
// 應(yīng)用啟動(dòng)類(lèi)
@SpringBootApplication
public class ProductApplication {
    public static void main(String[] args) {
        SpringApplication.run(ProductApplication.class, args);
    }
    @Autowired
    private ProductRepository productRepository;
    public void run(String... args) {
        // 初始化數(shù)據(jù)
        productRepository.save(new Product("P001", "手機(jī)", 1000.0, 100));
        productRepository.save(new Product("P002", "電腦", 5000.0, 50));
        productRepository.save(new Product("P003", "電視", 3000.0, 80));
        productRepository.save(new Product("P004", "手表", 500.0, 200));
        productRepository.save(new Product("P005", "耳機(jī)", 300.0, 150));
    }
}
// 測(cè)試類(lèi)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ProductApplicationTests {
    @LocalServerPort
    private int port;
    @Autowired
    private TestRestTemplate restTemplate;
    @Test
    void contextLoads() {
    }
    @Test
    void testHomePage() {
        String response = restTemplate.getForObject("http://localhost:" + port + "/products/", String.class);
        assertThat(response).contains("產(chǎn)品列表");
    }
}

輸出結(jié)果

  • 訪問(wèn)http://localhost:8080/products/:顯示產(chǎn)品列表頁(yè)面。
  • 訪問(wèn)http://localhost:8080/products/top-selling?topN=3:顯示銷(xiāo)量TOP3的產(chǎn)品列表頁(yè)面。

? 結(jié)論:在實(shí)際開(kāi)發(fā)中,Spring Boot視圖層與模板引擎的應(yīng)用場(chǎng)景非常廣泛,需要根據(jù)實(shí)際問(wèn)題選擇合適的模板引擎。

總結(jié)

本章我們學(xué)習(xí)了Spring Boot視圖層與模板引擎,包括Spring Boot視圖層的基本方法、Spring Boot與Thymeleaf的集成、Spring Boot與Freemarker的集成、Spring Boot與Velocity的集成、Spring Boot的靜態(tài)資源管理、Spring Boot的實(shí)際應(yīng)用場(chǎng)景,學(xué)會(huì)了在實(shí)際開(kāi)發(fā)中處理視圖層問(wèn)題。其中,Spring Boot視圖層的基本方法、Spring Boot與Thymeleaf的集成、Spring Boot與Freemarker的集成、Spring Boot與Velocity的集成、Spring Boot的靜態(tài)資源管理、Spring Boot的實(shí)際應(yīng)用場(chǎng)景是本章的重點(diǎn)內(nèi)容。從下一章開(kāi)始,我們將學(xué)習(xí)Spring Boot的其他組件、微服務(wù)等內(nèi)容。

到此這篇關(guān)于Spring Boot 視圖層與模板引擎的文章就介紹到這了,更多相關(guān)springboot模板引擎內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

菏泽市| 襄垣县| 定边县| 荆州市| 甘南县| 绍兴市| 抚顺市| 扎鲁特旗| 岳西县| 彭水| 柘荣县| 哈密市| 碌曲县| 罗平县| 万载县| 大庆市| 万州区| 张家港市| 沅陵县| 巴楚县| 泰安市| 桃江县| 松潘县| 隆尧县| 彩票| 伊吾县| 武山县| 龙口市| 静乐县| 临潭县| 达孜县| 娄底市| 方山县| 竹北市| 高雄市| 日土县| 克拉玛依市| 江西省| 新干县| 永宁县| 西平县|