RESTful API设计原则与实现示例详解

  import org.springframework.http.HttpStatus;

  import org.springframework.http.ResponseEntity;

  import org.springframework.web.bind.annotation.*;

  import java.util.ArrayList;

  import java.util.List;

  @RestController

  @RequestMapping("/users")

  public class UserController {

  private List users = new ArrayList<>();

  @GetMapping

  public ResponseEntity> getUsers() {

  return new ResponseEntity<>(users, HttpStatus.OK);

  }

  @GetMapping("/{id}")

  public ResponseEntity getUser(@PathVariable Long id) {

  User user = users.stream()

  .filter(u -> u.getId().equals(id))

  .findFirst()

  .orElse(null);

  if (user == null) {

  return new ResponseEntity<>(HttpStatus.NOT_FOUND);

  }

  return new ResponseEntity<>(user, HttpStatus.OK);

  }

  @PostMapping

  public ResponseEntity createUser(@RequestBody User newUser) {

  users.add(newUser);

  return new ResponseEntity<>(newUser, HttpStatus.CREATED);

  }

  @PutMapping("/{id}")

  public ResponseEntity updateUser(@PathVariable Long id, @RequestBody User updatedUser) {

  User user = users.stream()

  .filter(u -> u.getId().equals(id))

  .findFirst()

  .orElse(null);

  if (user == null) {

  return new ResponseEntity<>(HttpStatus.NOT_FOUND);

  }

  user.setName(updatedUser.getName());

  user.setEmail(updatedUser.getEmail());

  return new ResponseEntity<>(user, HttpStatus.OK);

  }

  @DeleteMapping("/{id}")

  public ResponseEntity deleteUser(@PathVariable Long id) {

  User user = users.stream()

  .filter(u -> u.getId().equals(id))

  .findFirst()

  .orElse(null);

  if (user == null) {

  return new ResponseEntity<>(HttpStatus.NOT_FOUND);

  }

  users.remove(user);

  return new ResponseEntity<>(HttpStatus.NO_CONTENT);

  }

  }