返回

Spring Boot 架子搭建,手把手教你搭建前后端分离项目

后端

在本文中,我们将介绍如何使用 Spring Boot 和 Spring Framework 来构建一个前后端分离的 Spring Boot 项目。我们将学习如何搭建一个强大的、可扩展的后端 API 和一个优雅、响应式的前端界面。

技术栈:

  • Spring Boot 2.7.0
  • Spring Framework 5.3.18
  • Java 11
  • Thymeleaf 3.0.11
  • Spring Security 5.7.2
  • JSON Web Token (JWT)

项目结构:

├── backend
│   ├── src
│   │   ├── main
│   │   │   ├── java
│   │   │   │   ├── com
│   │   │   │   │   ├── example
│   │   │   │   │   │   ├── Application.java
│   │   │   │   │   │   ├── controller
│   │   │   │   │   │   │   ├── UserController.java
│   │   │   │   │   │   ├── entity
│   │   │   │   │   │   │   ├── User.java
│   │   │   │   │   │   ├── repository
│   │   │   │   │   │   │   ├── UserRepository.java
│   │   │   │   │   │   ├── service
│   │   │   │   │   │   │   ├── UserService.java
│   │   │   │   │   │   │   └── UserServiceImpl.java
│   │   │   │   │   │   ├── util
│   │   │   │   │   │   │   ├── JwtUtil.java
│   │   │   │   │   │   └── config
│   │   │   │   │   │   ├── SecurityConfig.java
│   │   │   │   │   │   └── WebSecurityConfig.java
│   │   │   │   │   └── application.properties
│   │   │   │   │   └── pom.xml
├── frontend
│   ├── src
│   │   ├── main
│   │   │   ├── webapp
│   │   │   │   ├── index.html
│   │   │   │   ├── main.js
│   │   │   │   ├── style.css
│   │   │   │   └── favicon.ico
│   │   │   └── pom.xml
├── pom.xml

步骤:

  1. 创建一个新的 Spring Boot 项目。
  2. 添加必要的依赖项。
  3. 创建后端 API。
  4. 创建前端界面。
  5. 连接后端 API 和前端界面。
  6. 测试项目。

详细步骤:

1. 创建一个新的 Spring Boot 项目。

打开你的终端并输入以下命令:

mvn archetype:generate -DgroupId=com.example -DartifactId=spring-boot-project -DarchetypeArtifactId=spring-boot-maven-plugin -DarchetypeGroupId=org.springframework.boot -DinteractiveMode=false -Dpackage=com.example

这将创建一个新的 Spring Boot 项目。

2. 添加必要的依赖项。

打开项目中的 pom.xml 文件并添加以下依赖项:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</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-web</artifactId>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

3. 创建后端 API。

backend 模块中,创建以下类:

// UserController.java

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping
    public ResponseEntity<User> createUser(@RequestBody User user) {
        return ResponseEntity.ok(userService.createUser(user));
    }

    @GetMapping
    public ResponseEntity<List<User>> getAllUsers() {
        return ResponseEntity.ok(userService.getAllUsers());
    }

    @GetMapping("/{id}")
    public ResponseEntity<User> getUserById(@PathVariable Long id) {
        return ResponseEntity.ok(userService.getUserById(id));
    }

    @PutMapping("/{id}")
    public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User user) {
        return ResponseEntity.ok(userService.updateUser(id, user));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
        return ResponseEntity.noContent().build();
    }
}
// UserService.java

public interface UserService {

    User createUser(User user);

    List<User> getAllUsers();

    User getUserById(Long id);

    User updateUser(Long id, User user);

    void deleteUser(Long id);
}
// UserServiceImpl.java

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public User createUser(User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        return userRepository.save(user);
    }

    @Override
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    @Override
    public User getUserById(Long id) {
        return userRepository.findById(id).orElse(null);
    }

    @Override
    public User updateUser(Long id, User user) {
        User existingUser = userRepository.findById(id).orElse(null);
        existingUser.setName(user.getName());
        existingUser.setEmail(user.getEmail());
        existingUser.setPassword(passwordEncoder.encode(user.getPassword()));
        return userRepository.save(existingUser);
    }

    @Override
    public void deleteUser(Long id) {
        userRepository.deleteById(id);
    }
}
// UserRepository.java

public interface UserRepository extends JpaRepository<User, Long> {

    Optional<User> findByEmail(String email);
}
// User.java

@Entity
@Table(name = "users")
public class User {

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

    @Column(name = "name")
    private String name;

    @Column(name = "email", unique = true)
    private String email;

    @Column(name = "password")
    private String password;

    // getters and setters
}
// application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/spring_boot_project?useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update

4. 创建前端界面。

frontend 模块中,创建以下文件:

// index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <h1>Spring Boot Project</h1>

    <div id="users"></div>

    <script src="main.js"></script>
</body>
</html>
// main.js

const usersElement = document.getElementById("users");

const getAllUsers = () => {
    fetch