Spring Boot 視圖層與模板引擎的應(yīng)用方法
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集成的方法。
步驟:
- 在pom.xml文件中添加Thymeleaf依賴。
- 在application.properties或application.yml文件中配置Thymeleaf。
- 創(chuàng)建實(shí)體類(lèi)。
- 創(chuàng)建Repository接口。
- 創(chuàng)建控制器類(lèi)。
- 創(chuàng)建Thymeleaf模板文件。
- 測(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集成的方法。
步驟:
- 在pom.xml文件中添加Freemarker依賴。
- 在application.properties或application.yml文件中配置Freemarker。
- 創(chuàng)建實(shí)體類(lèi)。
- 創(chuàng)建Repository接口。
- 創(chuàng)建控制器類(lèi)。
- 創(chuàng)建Freemarker模板文件。
- 測(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集成的方法。
步驟:
- 在pom.xml文件中添加Velocity依賴。
- 在application.properties或application.yml文件中配置Velocity。
- 創(chuàng)建實(shí)體類(lèi)。
- 創(chuàng)建Repository接口。
- 創(chuàng)建控制器類(lèi)。
- 創(chuàng)建Velocity模板文件。
- 測(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)文章希望大家以后多多支持腳本之家!
- SpringBoot整合Thymeleaf模板引擎的實(shí)踐過(guò)程
- SpringBoot自帶模板引擎Thymeleaf使用示例詳解
- SpringBoot超詳細(xì)講解Thymeleaf模板引擎
- springboot學(xué)習(xí)之Thymeleaf模板引擎及原理介紹
- Java SpringBoot模板引擎之 Thymeleaf入門(mén)詳解
- SpringBoot使用Thymeleaf模板引擎訪問(wèn)靜態(tài)html的過(guò)程
- Springboot整合thymleaf模板引擎過(guò)程解析
- 詳解SpringBoot+Thymeleaf 基于HTML5的現(xiàn)代模板引擎
- SpringBoot整合Thymeleaf與FreeMarker視圖層技術(shù)
相關(guān)文章
springboot自動(dòng)配置原理以及spring.factories文件的作用詳解
這篇文章主要介紹了springboot自動(dòng)配置原理以及spring.factories文件的作用詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-10-10
springboot security自定義認(rèn)證過(guò)程
這篇文章主要介紹了springboot security自定義認(rèn)證過(guò)程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2025-03-03
Java實(shí)戰(zhàn)項(xiàng)目 醫(yī)院預(yù)約掛號(hào)系統(tǒng)
本文是一個(gè)Java語(yǔ)言編寫(xiě)的實(shí)戰(zhàn)項(xiàng)目,是一個(gè)醫(yī)院預(yù)約掛號(hào)系統(tǒng),主要用到了jdbc+jsp+mysql+ajax等技術(shù),技術(shù)含量比較高,感興趣的童鞋跟著小編往下看吧2021-09-09
Java中通過(guò)jsch來(lái)連接遠(yuǎn)程服務(wù)器執(zhí)行l(wèi)inux命令
這篇文章主要介紹了Java中通過(guò)jsch來(lái)連接遠(yuǎn)程服務(wù)器執(zhí)行l(wèi)inux命令的相關(guān)資料,需要的朋友可以參考下2016-03-03
關(guān)于feign調(diào)用的參數(shù)傳遞問(wèn)題(@RequestBody和@RequestParam)
這篇文章主要介紹了關(guān)于feign調(diào)用的參數(shù)傳遞問(wèn)題(@RequestBody和@RequestParam),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03
Springboot Thymeleaf數(shù)字對(duì)象使用方法
這篇文章主要介紹了Springboot Thymeleaf數(shù)字對(duì)象使用方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2007-09-09

