使用 Java 构建 RESTful API

1. 创建一个 Spring Boot 项目

你可以通过 Spring Initializr 网站生成一个 Spring Boot 项目,也可以通过命令行工具或 IDE(如 IntelliJ IDEA 或 Eclipse)创建。

  • 在 Spring Initializr 网站中选择项目的基本设置:
    • Project: Maven Project
    • Language: Java
    • Spring Boot Version: 最新稳定版(如 3.x.x)
    • Dependencies: 选择 Spring Web

点击“Generate”生成项目,然后解压下载的文件并导入到你的 IDE 中。

2. 项目结构

一个典型的 Spring Boot 项目结构如下:

src
│   ├── main
│   │   ├── java
│   │   │   └── com.example.demo
│   │   │       ├── DemoApplication.java  # 启动类
│   │   │       ├── controller
│   │   │       │   └── UserController.java  # 控制器类
│   │   │       ├── service
│   │   │       │   └── UserService.java  # 服务类
│   │   │       ├── model
│   │   │       │   └── User.java  # 实体类
│   │   │       ├── repository
│   │   │           └── UserRepository.java  # 数据库访问类
│   │   └── resources
│   │       ├── application.properties  # 配置文件

3. 编写实体类

model 包下创建一个实体类 User.java

package com.example.demo.model;

public class User {
    private Long id;
    private String name;
    private String email;

    // Getters and Setters
}

4. 创建控制器类

controller 包下创建一个控制器类 UserController.java

package com.example.demo.controller;

import com.example.demo.model.User;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

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

    private List<User> users = new ArrayList<>();

    @GetMapping
    public List<User> getAllUsers() {
        return users;
    }

    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return users.stream().filter(user -> user.getId().equals(id)).findFirst().orElse(null);
    }

    @PostMapping
    public User createUser(@RequestBody User user) {
        users.add(user);
        return user;
    }

    @PutMapping("/{id}")
    public User updateUser(@PathVariable Long id, @RequestBody User updatedUser) {
        User user = getUserById(id);
        if (user != null) {
            user.setName(updatedUser.getName());
            user.setEmail(updatedUser.getEmail());
        }
        return user;
    }

    @DeleteMapping("/{id}")
    public void deleteUser(@PathVariable Long id) {
        users.removeIf(user -> user.getId().equals(id));
    }
}

5. 启动应用程序

DemoApplication.java 中启动应用程序:

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);
    }
}

6. 运行和测试

运行项目后,API 将在 http://localhost:8080 上启动。你可以通过 PostmancURL 或浏览器访问以下 URL 进行测试:

  • GET /api/users - 获取所有用户
  • GET /api/users/{id} - 根据 ID 获取用户
  • POST /api/users - 创建新用户
  • PUT /api/users/{id} - 更新用户信息
  • DELETE /api/users/{id} - 删除用户

7. 添加持久化层(可选)

如果你希望将数据持久化到数据库中,可以使用 Spring Data JPA:

  • pom.xml 文件中添加依赖项:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>
  • 修改 User.java
package com.example.demo.model;

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

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

    // Getters and Setters
}
  • 创建 UserRepository.java
package com.example.demo.repository;

import com.example.demo.model.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {
}
  • 修改 UserController.java 使用 UserRepository
package com.example.demo.controller;

import com.example.demo.model.User;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

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

    @Autowired
    private UserRepository userRepository;

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

    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return userRepository.findById(id).orElse(null);
    }

    @PostMapping
    public User createUser(@RequestBody User user) {
        return userRepository.save(user);
    }

    @PutMapping("/{id}")
    public User updateUser(@PathVariable Long id, @RequestBody User updatedUser) {
        User user = getUserById(id);
        if (user != null) {
            user.setName(updatedUser.getName());
            user.setEmail(updatedUser.getEmail());
            return userRepository.save(user);
        }
        return null;
    }

    @DeleteMapping("/{id}")
    public void deleteUser(@PathVariable Long id) {
        userRepository.deleteById(id);
    }
}

8. 配置文件 (application.yml)

src/main/resources 目录下找到或创建 application.yml 文件,并添加以下内容来配置 MySQL 数据库连接:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/your_database_name?useSSL=false&serverTimezone=UTC
    username: your_username
    password: your_password
    driver-class-name: com.mysql.cj.jdbc.Driver

  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
    database-platform: org.hibernate.dialect.MySQL8Dialect

server:
  port: 8080

 确保有Mysql驱动依赖

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

愿时光不负.

爱意随风起,风止意难平。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值