[SpringBoot] Spring MVC (6.0) —— 图书管理系统(初)

在这篇文章中,我们将介绍如何使用 Spring Boot 和 Spring MVC (6.0) 来构建一个简单的图书管理系统。这个系统的主要功能是:展示图书列表、添加新图书、更新图书信息以及删除图书。随着项目的逐步开发,我们还将引入更多的功能和复杂的技术,如数据库、前端页面、用户认证等。

本示例的主要特性:

  • 使用 Spring Boot 6.0 构建后端服务。
  • 使用 Spring MVC 模块处理 HTTP 请求。
  • 简单的 REST API 和 Thymeleaf 前端模板引擎来显示图书信息。

项目结构

book-management-system/
├── src/
│   ├── main/
│   │   ├── java/
│   │   │   └── com/
│   │   │       └── example/
│   │   │           └── bookmanagement/
│   │   │               ├── BookManagementApplication.java
│   │   │               ├── controller/
│   │   │               │   └── BookController.java
│   │   │               ├── model/
│   │   │               │   └── Book.java
│   │   │               ├── repository/
│   │   │               │   └── BookRepository.java
│   │   │               └── service/
│   │   │                   └── BookService.java
│   └── resources/
│       ├── application.properties
│       ├── templates/
│       │   └── book-list.html
│       └── static/
│           └── css/
│               └── style.css
└── pom.xml

1. 设置 Spring Boot 项目

首先,使用 Spring Initializr 创建一个基本的 Spring Boot 项目。我们将选择以下依赖:

  • Spring Web
  • Thymeleaf
  • Spring Data JPA
  • H2 Database(作为内存数据库)

pom.xml 配置

<dependencies>
    <!-- Spring Boot Starter Web, 包括 Spring MVC -->
    <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>

    <!-- Spring Data JPA 用于数据库操作 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

    <!-- H2 Database -->
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>

    <!-- Spring Boot Starter Test -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

2. 编写 Book 模型类

package com.example.bookmanagement.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String title;
    private String author;
    private String description;

    public Book() {
    }

    public Book(String title, String author, String description) {
        this.title = title;
        this.author = author;
        this.description = description;
    }

    // Getters and Setters
}

3. 创建 BookRepository 接口

package com.example.bookmanagement.repository;

import com.example.bookmanagement.model.Book;
import org.springframework.data.jpa.repository.JpaRepository;

public interface BookRepository extends JpaRepository<Book, Long> {
}

4. 创建 BookService 服务类

package com.example.bookmanagement.service;

import com.example.bookmanagement.model.Book;
import com.example.bookmanagement.repository.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class BookService {

    private final BookRepository bookRepository;

    @Autowired
    public BookService(BookRepository bookRepository) {
        this.bookRepository = bookRepository;
    }

    public List<Book> getAllBooks() {
        return bookRepository.findAll();
    }

    public Optional<Book> getBookById(Long id) {
        return bookRepository.findById(id);
    }

    public Book saveBook(Book book) {
        return bookRepository.save(book);
    }

    public void deleteBook(Long id) {
        bookRepository.deleteById(id);
    }
}

5. 创建 BookController 控制器类

package com.example.bookmanagement.controller;

import com.example.bookmanagement.model.Book;
import com.example.bookmanagement.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/books")
public class BookController {

    private final BookService bookService;

    @Autowired
    public BookController(BookService bookService) {
        this.bookService = bookService;
    }

    // 显示所有图书
    @GetMapping
    public String getAllBooks(Model model) {
        model.addAttribute("books", bookService.getAllBooks());
        return "book-list";
    }

    // 显示添加图书页面
    @GetMapping("/new")
    public String showAddBookForm(Model model) {
        model.addAttribute("book", new Book());
        return "book-form";
    }

    // 处理添加图书请求
    @PostMapping
    public String addBook(@ModelAttribute Book book) {
        bookService.saveBook(book);
        return "redirect:/books";
    }

    // 显示编辑图书页面
    @GetMapping("/edit/{id}")
    public String showEditBookForm(@PathVariable Long id, Model model) {
        model.addAttribute("book", bookService.getBookById(id).orElse(null));
        return "book-form";
    }

    // 处理编辑图书请求
    @PostMapping("/edit/{id}")
    public String editBook(@PathVariable Long id, @ModelAttribute Book book) {
        book.setId(id);
        bookService.saveBook(book);
        return "redirect:/books";
    }

    // 处理删除图书请求
    @GetMapping("/delete/{id}")
    public String deleteBook(@PathVariable Long id) {
        bookService.deleteBook(id);
        return "redirect:/books";
    }
}

6. 创建 book-list.html 页面(显示图书列表)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>图书管理系统</title>
    <link rel="stylesheet" type="text/css" href="/css/style.css">
</head>
<body>
    <h1>图书管理系统</h1>

    <a href="/books/new">添加新图书</a>
    
    <table>
        <thead>
            <tr>
                <th>标题</th>
                <th>作者</th>
                <th>描述</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            <tr th:each="book : ${books}">
                <td th:text="${book.title}"></td>
                <td th:text="${book.author}"></td>
                <td th:text="${book.description}"></td>
                <td>
                    <a th:href="@{/books/edit/{id}(id=${book.id})}">编辑</a> |
                    <a th:href="@{/books/delete/{id}(id=${book.id})}">删除</a>
                </td>
            </tr>
        </tbody>
    </table>
</body>
</html>

7. 创建 book-form.html 页面(添加/编辑图书表单)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>图书表单</title>
    <link rel="stylesheet" type="text/css" href="/css/style.css">
</head>
<body>
    <h1 th:text="${book.id == null ? '添加' : '编辑'} + '图书'"></h1>

    <form th:action="@{${book.id == null ? '/books' : '/books/edit/' + book.id}}" method="post">
        <label for="title">标题:</label>
        <input type="text" id="title" name="title" th:value="${book.title}" required />
        
        <label for="author">作者:</label>
        <input type="text" id="author" name="author" th:value="${book.author}" required />
        
        <label for="description">描述:</label>
        <textarea id="description" name="description" th:value="${book.description}" required></textarea>

        <button type="submit">提交</button>
   

8. 配置 application.properties

# H2 数据库配置(内存数据库)
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
spring.jpa.hibernate.ddl-auto=update

9. 启动应用程序

在 BookManagementApplication.java 中添加 @SpringBootApplication 注解并启动应用:

package com.example.bookmanagement;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class BookManagementApplication {

    public static void main(String[] args) {
        SpringApplication.run(BookManagementApplication.class, args);
    }
}

结语

至此,我们已经完成了一个简单的图书管理系统的初步开发。我们使用了 Spring Boot 和 Spring MVC 6.0,并通过 Spring Data JPA 操作数据库,实现了图书的增、删、改、查功能。接下来,可以根据需求扩展更多功能,比如用户认证、分页查询、图书分类等。