JavaWeb RESTful 开发规范入门

目录

[一、什么是 RESTful 规范](#一、什么是 RESTful 规范)

二、工程技术选型

三、项目结构

四、代码示例


一、什么是 RESTful 规范

REST(Representational State Transfer)是一种基于 HTTP 协议的架构风格,核心思想是将服务看作资源(Resource),通过统一的 URI(统一资源标识符)进行访问,并使用 HTTP 的四个动词(GET、POST、PUT、DELETE)来对资源执行不同的操作。遵循 RESTful 规范,可以让 API 具有良好的可读性、可维护性和可扩展性。

二、工程技术选型

  • 框架:Spring Boot(简化配置,快速搭建)

  • 依赖管理:Maven

  • 语言:Java 11+,配置文件为 properties(或 YAML)


三、项目结构

java 复制代码
demo-restful/
├── pom.xml
└── src
    └── main
        ├── java
        │   └── com.example.demo
        │       ├── DemoApplication.java
        │       ├── model
        │       │   └── User.java
        │       └── controller
        │           └── UserController.java
        └── resources
            └── application.properties

四、代码示例

提示:下面标注了文件名和代码语言,方便直接复制粘贴。

XML 复制代码
<!-- 文件:pom.xml -->
<!-- 语言: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>demo-restful</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.7.12</version>
  </parent>
  <dependencies>
    <!-- Web Starter 包含了 Spring MVC 和内嵌 Tomcat -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- Lombok 用于简化模型类写法(可选) -->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <optional>true</optional>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <!-- 插件:打包为可执行 Jar -->
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</project>
java 复制代码
// 文件:src/main/java/com/example/demo/DemoApplication.java
// 语言: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);
  }
}
java 复制代码
// 文件:src/main/java/com/example/demo/model/User.java
// 语言:Java
package com.example.demo.model;

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

  public User() {}
  public User(Long id, String name, String email) {
    this.id = id;
    this.name = name;
    this.email = email;
  }
  // getter & setter
  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; }
}
java 复制代码
// 文件:src/main/java/com/example/demo/controller/UserController.java
// 语言:Java
package com.example.demo.controller;

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

import java.util.*;

// @RestController = @Controller + @ResponseBody
@RestController
@RequestMapping("/users")
public class UserController {

  // 模拟内存中的用户列表
  private static final Map<Long, User> USER_MAP = Collections.synchronizedMap(new LinkedHashMap<>());
  static {
    USER_MAP.put(1L, new User(1L, "Alice", "alice@example.com"));
    USER_MAP.put(2L, new User(2L, "Bob", "bob@example.com"));
  }

  // GET /users     ------ 查询所有用户
  @GetMapping
  public List<User> list() {
    return new ArrayList<>(USER_MAP.values());
  }

  // GET /users/{id} ------ 根据 ID 查询
  @GetMapping("/{id}")
  public ResponseEntity<User> getById(@PathVariable Long id) {
    User u = USER_MAP.get(id);
    if (u != null) {
      return ResponseEntity.ok(u);
    }
    return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
  }

  // POST /users    ------ 新增用户(请求体 JSON)
  @PostMapping
  public ResponseEntity<User> create(@RequestBody User user) {
    long nextId = USER_MAP.keySet().stream().max(Long::compare).orElse(0L) + 1;
    user.setId(nextId);
    USER_MAP.put(nextId, user);
    return ResponseEntity.status(HttpStatus.CREATED).body(user);
  }

  // PUT /users/{id} ------ 更新用户
  @PutMapping("/{id}")
  public ResponseEntity<User> update(@PathVariable Long id, @RequestBody User user) {
    if (!USER_MAP.containsKey(id)) {
      return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
    }
    user.setId(id);
    USER_MAP.put(id, user);
    return ResponseEntity.ok(user);
  }

  // DELETE /users/{id} ------ 删除用户
  @DeleteMapping("/{id}")
  public ResponseEntity<Void> delete(@PathVariable Long id) {
    USER_MAP.remove(id);
    return ResponseEntity.noContent().build();
  }
}
XML 复制代码
# 文件:src/main/resources/application.properties
# 语言:Properties
server.port=8080
spring.jackson.serialization.indent_output=true   # JSON 输出格式化

五、运行并测试

  1. 打包启动

    java 复制代码
    mvn clean package
    java -jar target/demo-restful-0.0.1-SNAPSHOT.jar
  2. 测试示例(使用 curl)

    • 查询所有用户

      java 复制代码
      curl -i http://localhost:8080/users

      响应结果(HTTP/1.1 200 OK + JSON 列表)

      java 复制代码
      [
        {
          "id": 1,
          "name": "Alice",
          "email": "alice@example.com"
        },
        {
          "id": 2,
          "name": "Bob",
          "email": "bob@example.com"
        }
      ]
    • 根据 ID 查询

      java 复制代码
      curl -i http://localhost:8080/users/1

      响应结果(HTTP/1.1 200 OK + 单个 JSON)

      java 复制代码
      {
        "id": 1,
        "name": "Alice",
        "email": "alice@example.com"
      }
    • 新增用户

      java 复制代码
      curl -i -X POST -H "Content-Type: application/json" \
        -d '{"name":"Charlie","email":"charlie@example.com"}' \
        http://localhost:8080/users

      响应结果(HTTP/1.1 201 Created)

      java 复制代码
      {
        "id": 3,
        "name": "Charlie",
        "email": "charlie@example.com"
      }
    • 更新用户

      java 复制代码
      curl -i -X PUT -H "Content-Type: application/json" \
        -d '{"name":"Alice Smith","email":"alice.smith@example.com"}' \
        http://localhost:8080/users/1

      响应结果(HTTP/1.1 200 OK)

      java 复制代码
      {
        "id": 1,
        "name": "Alice Smith",
        "email": "alice.smith@example.com"
      }
    • 删除用户

      java 复制代码
      curl -i -X DELETE http://localhost:8080/users/2

      响应结果(HTTP/1.1 204 No Content)


六、小结

  • URI 设计:名词复数(/users),层级清晰

  • 动词与 HTTP 方法映射:GET/POST/PUT/DELETE 对应 查询/新增/更新/删除

  • 状态码:200、201、204、404 等要符合语义

  • 请求/响应格式 :JSON,使用 @RequestBody / @ResponseBody 自动序列化

遵循以上规范,能让你的 Java Web RESTful 接口更清晰易维护,也方便前后端分离项目的协作开发。

相关推荐
Penge6666 小时前
Go 接口编译期断言
后端
我是一颗柠檬6 小时前
【MySQL全面教学】MySQL面试高频考点汇总Day15(2026年)
数据库·后端·mysql·面试
橙淮6 小时前
并发编程(六)
java·jvm
拽着尾巴的鱼儿6 小时前
springboot openfeign 自定义feign 接口重试机制
java·spring boot·后端
白露与泡影7 小时前
2026大厂Java面试题大全!牛客网最新版
java·开发语言
Ceelog7 小时前
久坐党自救指南:屏幕前 8 小时,身体到底在经历什么
前端·后端
凯瑟琳.奥古斯特7 小时前
高阶子查询题目精炼
开发语言·数据库·python·职场和发展·数据库开发
身如柳絮随风扬7 小时前
数据库读写分离:从原理到实战,构建高并发系统
数据库·mysql
EntyIU7 小时前
JVM内存与GC笔记
java·jvm·笔记