引言
第一步:设置开发环境
1. 安装必要的软件
- JDK (Java Development Kit):推荐使用最新稳定版本
- IDE(Integrated Development Environment):推荐使用IntelliJ IDEA或Eclipse。
- Maven:确保安装并配置了Maven,用于依赖管理和构建项目
- MySQL:安装并运行MySQL数据库服务器。
- Git(可选):用于版本控制。
2. 创建项目结构
打开IDE,选择创建一个新的Maven项目,如果使用的是 IntelliJ IDEA,可以通过 File -> New -> Project
选择 Maven 项目类型,并指定 JDK 版本和项目名称。
3. 添加必要依赖
以 Spring Boot 为例,因为它简化了配置过程并提供了许多开箱即用的功能,在pom.xml
文件中添加以下内容:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>myapp</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
4. 配置数据库连接
在src/main/resources/application.properties
文件中添加数据库连接信息:
spring.datasource.url=jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=yourpassword
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.thymeleaf.cache=false
第二步:设计数据模型
1. 创建实体类
在src/main/java/com/example/myapp/model
目录下创建一个简单的实体类User.java
,它将映射到数据库表中:
package com.example.myapp.model;
import javax.persistence.*;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// Getters and Setters
}
2. 创建Repository接口
在src/main/java/com/example/myapp/repository
目录下创建一个UserRepository.java
接口:
package com.example.myapp.repository;
import com.example.myapp.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
}
第三步:创建服务层
1. 创建服务接口
为为User
实体创建 JPA 仓库接口,在src/main/java/com/example/myapp/service
目录下创建一个UserService.java
接口:
package com.example.myapp.service;
import com.example.myapp.model.User;
import java.util.List;
public interface UserService {
List<User> findAll();
User save(User user);
void delete(Long id);
}
2. 实现服务接口
编写服务类来处理业务逻辑,创建 REST 控制器来处理 HTTP 请求,在同一目录下创建一个UserServiceImpl.java
实现类:
package com.example.myapp.service;
import com.example.myapp.model.User;
import com.example.myapp.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Override
public List<User> findAll() {
return userRepository.findAll();
}
@Override
public User save(User user) {
return userRepository.save(user);
}
@Override
public void delete(Long id) {
userRepository.deleteById(id);
}
}
第四步:创建控制器
1. 创建控制器类
创建 REST 控制器来处理 HTTP 请求,在src/main/java/com/example/myapp/controller
目录下创建一个UserController.java
控制器类:
package com.example.myapp.controller;
import com.example.myapp.model.User;
import com.example.myapp.service.UserService;
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
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/")
public String index(Model model) {
List<User> users = userService.findAll();
model.addAttribute("users", users);
return "index";
}
@PostMapping("/add")
public String addUser(@ModelAttribute User user) {
userService.save(user);
return "redirect:/";
}
@GetMapping("/delete/{id}")
public String deleteUser(@PathVariable Long id) {
userService.delete(id);
return "redirect:/";
}
}
第五步:创建视图
1. 创建HTML模板
使用 Thymeleaf 模板引擎创建前端页面,在src/main/resources/templates
目录下创建一个index.html
文件:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>User Management</title>
</head>
<body>
<h1>User List</h1>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr th:each="user : ${users}">
<td th:text="${user.id}"></td>
<td th:text="${user.name}"></td>
<td th:text="${user.email}"></td>
<td>
<a th:href="@{/delete/{id}(id=${user.id})}" onclick="return confirm('Are you sure?')">Delete</a>
</td>
</tr>
</tbody>
</table>
<form method="post" action="/add">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<button type="submit">Add User</button>
</form>
</body>
</html>
同时更新控制器以支持视图渲染:
@Controller
public class WebController {
@Autowired
private UserService userService;
@GetMapping("/")
public String index(Model model) {
model.addAttribute("users", userService.getAllUsers());
return "index";
}
}
第六步:运行和测试
最后,在主类中启动 Spring Boot 应用程序:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
运行 DemoApplication
类中的 main
方法,访问 http://localhost:8080/
查看结果,能看到用户列表页面,并且可以添加和删除用户。