Bootstrap

Spring MVC构建的简单信息管理系统示例

1. 项目结构

项目结构如下:

src
├── main
│   ├── java
│   │   └── com
│   │       └── example
│   │           └── infomanagement
│   │               ├── controller
│   │               │   └── InfoController.java
│   │               ├── model
│   │               │   └── Info.java
│   │               ├── repository
│   │               │   └── InfoRepository.java
│   │               ├── service
│   │               │   └── InfoService.java
│   │               └── InfomanagementApplication.java
│   └── resources
│       ├── templates
│       │   ├── edit.html
│       │   ├── index.html
│       │   ├── new.html
│       └── application.properties
└── test
    └── java
        └── com
            └── example
                └── infomanagement
                    └── InfomanagementApplicationTests.java

2. 代码实现

InfomanagementApplication.java

package com.example.infomanagement;

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

@SpringBootApplication
public class InfomanagementApplication {

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

Info.java

package com.example.infomanagement.model;

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

@Entity
public class Info {
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;
    private String email;

    // Getters and Setters
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

InfoRepository.java

package com.example.infomanagement.repository;

import com.example.infomanagement.model.Info;
import org.springframework.data.repository.CrudRepository;

public interface InfoRepository extends CrudRepository<Info, Long> {
}

InfoService.java

package com.example.infomanagement.service;

import com.example.infomanagement.model.Info;
import com.example.infomanagement.repository.InfoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class InfoService {
    
    @Autowired
    private InfoRepository infoRepository;

    public Iterable<Info> getAllInfo() {
        return infoRepository.findAll();
    }

    public Info getInfoById(Long id) {
        return infoRepository.findById(id).orElse(null);
    }

    public void saveInfo(Info info) {
        infoRepository.save(info);
    }

    public void deleteInfo(Long id) {
        infoRepository.deleteById(id);
    }
}

InfoController.java

package com.example.infomanagement.controller;

import com.example.infomanagement.model.Info;
import com.example.infomanagement.service.InfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
public class InfoController {
    
    @Autowired
    private InfoService infoService;

    @GetMapping("/")
    public String viewHomePage(Model model) {
        model.addAttribute("allInfo", infoService.getAllInfo());
        return "index";
    }

    @GetMapping("/new")
    public String showNewInfoForm(Model model) {
        Info info = new Info();
        model.addAttribute("info", info);
        return "new";
    }

    @PostMapping("/save")
    public String saveInfo(@ModelAttribute("info") Info info) {
        infoService.saveInfo(info);
        return "redirect:/";
    }

    @GetMapping("/edit/{id}")
    public String showEditInfoForm(@PathVariable("id") Long id, Model model) {
        Info info = infoService.getInfoById(id);
        model.addAttribute("info", info);
        return "edit";
    }

    @PostMapping("/update/{id}")
    public String updateInfo(@PathVariable("id") Long id, @ModelAttribute("info") Info info) {
        info.setId(id);
        infoService.saveInfo(info);
        return "redirect:/";
    }

    @GetMapping("/delete/{id}")
    public String deleteInfo(@PathVariable("id") Long id) {
        infoService.deleteInfo(id);
        return "redirect:/";
    }
}

index.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>信息管理系统</title>
</head>
<body>
    <h2>信息管理系统</h2>
    <table border="1">
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
            <th>Actions</th>
        </tr>
        <tr th:each="info : ${allInfo}">
            <td th:text="${info.id}">1</td>
            <td th:text="${info.name}">John Doe</td>
            <td th:text="${info.email}">john@example.com</td>
            <td>
                <a th:href="@{/edit/{id}(id=${info.id})}">Edit</a>
                <a th:href="@{/delete/{id}(id=${info.id})}">Delete</a>
            </td>
        </tr>
    </table>
    <br>
    <a href="/new">Add New Info</a>
</body>
</html>

new.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>添加新信息</title>
</head>
<body>
    <h2>添加新信息</h2>
    <form th:action="@{/save}" th:object="${info}" method="post">
        <label>Name:</label>
        <input type="text" th:field="*{name}" />
        <br>
        <label>Email:</label>
        <input type="email" th:field="*{email}" />
        <br>
        <input type="submit" value="Save" />
    </form>
</body>
</html>

edit.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>编辑信息</title>
</head>
<body>
    <h2>编辑信息</h2>
    <form th:action="@{/update/{id}(id=${info.id})}" th:object="${info}" method="post">
        <label>Name:</label>
        <input type="text" th:field="*{name}" />
        <br>
        <label>Email:</label>
        <input type="email" th:field="*{email}" />
        <br>
        <input type="submit" value="Update" />
    </form>
</body>
</html>

application.properties

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.h2.console.enabled=true
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update

;