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

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

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

Spring Boot 視圖層與模板引擎

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

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

19.2 Spring Boot視圖層概述

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

19.2.1 視圖層的定義

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

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

? 結(jié)論:視圖層是指使用Spring Boot進(jìn)行Web應(yīng)用開發(fā)的方法,作用是實現(xiàn)Web頁面的渲染、數(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)建實體類。
  4. 創(chuàng)建Repository接口。
  5. 創(chuàng)建控制器類。
  6. 創(chuàng)建Thymeleaf模板文件。
  7. 測試應(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ù)庫依賴 -->
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
    <!-- 測試依賴 -->
    <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ù)庫連接信息
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ù)庫控制臺
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

實體類:

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);
}

控制器類:

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>價格:</label>
            <input type="number" th:field="*{price}" step="0.01" required>
            <label>銷量:</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>銷量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>價格</th>
                <th>銷量</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>

測試類:

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)建實體類、創(chuàng)建Repository接口、創(chuàng)建控制器類、創(chuàng)建Thymeleaf模板文件、測試應(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)建實體類。
  4. 創(chuàng)建Repository接口。
  5. 創(chuàng)建控制器類。
  6. 創(chuàng)建Freemarker模板文件。
  7. 測試應(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ù)庫依賴 -->
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
    <!-- 測試依賴 -->
    <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ù)庫連接信息
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ù)庫控制臺
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

實體類、Repository接口、控制器類與集成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>價格:</label>
            <input type="number" name="price" step="0.01" required>
            <label>銷量:</label>
            <input type="number" name="sales" required>
            <button type="submit">添加產(chǎn)品</button>
        </form>
    </div>
    <div>
        <form action="/products/top-selling" method="get">
            <label>銷量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>價格</th>
                <th>銷量</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>

測試類:

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)建實體類、創(chuàng)建Repository接口、創(chuàng)建控制器類、創(chuàng)建Freemarker模板文件、測試應(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)建實體類。
  4. 創(chuàng)建Repository接口。
  5. 創(chuàng)建控制器類。
  6. 創(chuàng)建Velocity模板文件。
  7. 測試應(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ù)庫依賴 -->
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
    <!-- 測試依賴 -->
    <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ù)庫連接信息
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ù)庫控制臺
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

實體類、Repository接口、控制器類與集成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>價格:</label>
            <input type="number" name="price" step="0.01" required>
            <label>銷量:</label>
            <input type="number" name="sales" required>
            <button type="submit">添加產(chǎn)品</button>
        </form>
    </div>
    <div>
        <form action="/products/top-selling" method="get">
            <label>銷量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>價格</th>
                <th>銷量</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>

測試類:

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)建實體類、創(chuàng)建Repository接口、創(chuàng)建控制器類、創(chuàng)建Velocity模板文件、測試應(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、圖片等。
  • 提高開發(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>價格:</label>
            <input type="number" th:field="*{price}" step="0.01" required>
            <label>銷量:</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>銷量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>價格</th>
                <th>銷量</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的實際應(yīng)用場景

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

  • 實現(xiàn)商品的展示與購買。
  • 實現(xiàn)訂單的管理。
  • 實現(xiàn)用戶的管理。
  • 實現(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)品類
@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)用啟動類
@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));
    }
}
// 測試類
@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é)果

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

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

總結(jié)

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

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

相關(guān)文章

最新評論

甘谷县| 青州市| 闽清县| 丽江市| 邵阳市| 万州区| 靖边县| 安西县| 武陟县| 永城市| 宜黄县| 永新县| 绥棱县| 临猗县| 民县| 泸定县| 凤翔县| 长沙市| 香格里拉县| 儋州市| 鲁山县| 鄂伦春自治旗| 洪湖市| 林口县| 手机| 图木舒克市| 尚志市| 凤庆县| 延边| 旬阳县| 新巴尔虎左旗| 临西县| 织金县| 佳木斯市| 乌鲁木齐县| 乳山市| 连山| 东明县| 苍梧县| 顺平县| 龙游县|