HTTP协议及Spring Boot RESTful接口设计
1. HTTP协议概述
HTTP(HyperText Transfer Protocol)是一个无状态的应用层协议,主要用于客户端与服务器之间的数据传输。
2. 常见HTTP请求方法
GET
用于获取资源。请求的数据附加在URL中。
POST
用于提交数据,数据包含在请求体中。适用于表单提交、文件上传等。
PUT
用于更新资源。将请求体中的数据替换服务器上的资源。
DELETE
用于删除资源。
3. HTTP状态码
2xx - 请求成功
- 200 OK
- 201 Created
3xx - 重定向
- 301 Moved Permanently
- 302 Found
4xx - 客户端错误
- 400 Bad Request
- 404 Not Found
5xx - 服务器错误
- 500 Internal Server Error
HTTP 方法
HTTP 协议中常见的请求方法有:
- GET: 请求获取资源,通常用于查询操作。
- POST: 请求提交数据,通常用于创建资源。
- PUT: 请求更新资源,通常用于替换指定的资源。
- DELETE: 请求删除资源。
HTTP 状态码
- 200 OK: 请求成功,响应内容在消息体中。
- 201 Created: 请求成功,资源已被创建。
- 400 Bad Request: 请求格式错误。
- 404 Not Found: 请求的资源未找到。
- 500 Internal Server Error: 服务器内部错误。
请求与响应的结构
- 请求:包含方法、URL、头部、请求体。
- 响应:包含状态码、头部、响应体。
4. RESTful架构原则
- 资源通过URI唯一标识
- 请求无状态
- 使用标准HTTP方法(GET、POST、PUT、DELETE等)
1. RESTful API 的设计原则
- 资源(Resource): 在REST中,资源是系统中的对象,如用户、商品、订单等。每个资源通过URL唯一标识。
- 无状态(Stateless): 客户端与服务器之间的通信是无状态的,每次请求都必须包含处理请求所需的所有信息。
- 统一接口(Uniform Interface): RESTful API使用统一的URL和HTTP方法操作资源。
2. 常见RESTful设计模式
- GET /users: 获取所有用户。
- GET /users/{id}: 根据ID获取单个用户。
- POST /users: 创建新用户。
- PUT /users/{id}: 更新用户信息。
- DELETE /users/{id}: 删除指定用户。
5. Spring Boot中HTTP方法示例
@RestController
@RequestMapping("/api/products")
public class ProductController {
@GetMapping
public List<Product> getAllProducts() {
return productService.getAllProducts();
}
@GetMapping("/{id}")
public Product getProductById(@PathVariable Long id) {
return productService.getProductById(id);
}
@PostMapping
public Product createProduct(@RequestBody Product product) {
return productService.createProduct(product);
}
@PutMapping("/{id}")
public Product updateProduct(@PathVariable Long id, @RequestBody Product product) {
return productService.updateProduct(id, product);
}
@DeleteMapping("/{id}")
public void deleteProduct(@PathVariable Long id) {
productService.deleteProduct(id);
}
}6.Spring Boot 实现 RESTful API
实体类定义:User
定义用户实体类,用来接收和返回用户数据。
java复制编辑package com.example.usermanagement.model;
public class User {
private Long id;
private String name;
private String email;
// 构造方法、Getter 和 Setter
public User(Long id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
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;
}
}服务层:UserService
服务层负责业务逻辑处理,模拟用户数据存储。
java复制编辑package com.example.usermanagement.service;
import com.example.usermanagement.model.User;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
public class UserService {
private List<User> users = new ArrayList<>();
public UserService() {
users.add(new User(1L, "John Doe", "john@example.com"));
users.add(new User(2L, "Jane Smith", "jane@example.com"));
}
public List<User> getAllUsers() {
return users;
}
public Optional<User> getUserById(Long id) {
return users.stream().filter(user -> user.getId().equals(id)).findFirst();
}
public User createUser(User user) {
users.add(user);
return user;
}
public Optional<User> updateUser(Long id, User user) {
Optional<User> existingUser = getUserById(id);
existingUser.ifPresent(u -> {
u.setName(user.getName());
u.setEmail(user.getEmail());
});
return existingUser;
}
public boolean deleteUser(Long id) {
return users.removeIf(user -> user.getId().equals(id));
}
}控制器层:UserController
控制器层用于处理HTTP请求,并调用服务层进行数据处理。
java复制编辑package com.example.usermanagement.controller;
import com.example.usermanagement.model.User;
import com.example.usermanagement.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping
public List<User> getAllUsers() {
return userService.getAllUsers();
}
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
return userService.getUserById(id).orElse(null);
}
@PostMapping
public User createUser(@RequestBody User user) {
return userService.createUser(user);
}
@PutMapping("/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User user) {
return userService.updateUser(id, user).orElse(null);
}
@DeleteMapping("/{id}")
public boolean deleteUser(@PathVariable Long id) {
return userService.deleteUser(id);
}
}使用APIPost进行测试
1. 获取所有用户(GET请求)
- URL:
http://localhost:8080/users - 方法:GET
预期响应:
json复制编辑[ { "id": 1, "name": "John Doe", "email": "john@example.com" }, { "id": 2, "name": "Jane Smith", "email": "jane@example.com" } ]
2. 获取单个用户(GET请求)
- URL:
http://localhost:8080/users/1 - 方法:GET
预期响应:
json复制编辑{ "id": 1, "name": "John Doe", "email": "john@example.com" }
3. 创建用户(POST请求)
- URL:
http://localhost:8080/users - 方法:POST
请求体:
{ "id": 3, "name": "Alice Johnson", "email": "alice@example.com" }预期响应:
{ "id": 3, "name": "Alice Johnson", "email": "alice@example.com" }
4. 更新用户(PUT请求)
- URL:
http://localhost:8080/users/3 - 方法:PUT
请求体:
{ "name": "Alice Smith", "email": "alice.smith@example.com" }预期响应:
{ "id": 3, "name": "Alice Smith", "email": "alice.smith@example.com" }
5. 删除用户(DELETE请求)
- URL:
http://localhost:8080/users/3 - 方法:DELETE
- 预期响应:
true