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 接口更清晰易维护,也方便前后端分离项目的协作开发。

相关推荐
unique_perfect19 分钟前
vue2与springboot实现deepseek打印机聊天
spring boot·websocket·ai·vue2·deepseek
java1234_小锋24 分钟前
Spring IoC的实现机制是什么?
java·后端·spring
YJlio27 分钟前
Active Directory 工具学习笔记(10.8):AdInsight——保存与导出(证据留存、共享与二次分析)
数据库·笔记·学习
suoyue_zhan32 分钟前
GBase的管理监控平台GEM实践指南
数据库
喵个咪34 分钟前
开箱即用的 GoWind Admin|风行,企业级前后端一体中后台框架:JWT 集成指南
后端·go
绝不收费—免费看不了了联系我1 小时前
Fastapi的单进程响应问题 和 解决方法
开发语言·后端·python·fastapi
xqqxqxxq1 小时前
背单词软件技术笔记(V2.0扩展版)
java·笔记·python
喵个咪1 小时前
开箱即用的 GoWind Admin|风行,企业级前后端一体中后台框架:OPA 集成指南:从原理到实践
后端·go
消失的旧时光-19431 小时前
深入理解 Java 线程池(二):ThreadPoolExecutor 执行流程 + 运行状态 + ctl 原理全解析
java·开发语言
哈哈老师啊1 小时前
Springboot学生综合测评系统hxtne(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
java·数据库·spring boot