Bài này xây API quản lý sinh viên: các phương thức GET, POST, PUT, DELETE, đọc tham số đường dẫn, truy vấn, thân yêu cầu JSON và trả mã trạng thái phù hợp.

55 phútTrung cấp
Bạn sẽ học được
  • @GetMapping, @PostMapping, @PutMapping, @DeleteMapping
  • @PathVariable, @RequestParam, @RequestBody
  • ResponseEntity và mã trạng thái
  • record làm DTO

Cơ sở lý thuyết

Spring MVC xử lý yêu cầu qua một bộ điều phối trung tâm – DispatcherServlet (mẫu Front Controller): nhận mọi yêu cầu → tìm handler phù hợp theo ánh xạ (@GetMapping...) → gọi phương thức controller → chuyển giá trị trả về thành phản hồi.

  • @RestController = @Controller + @ResponseBody: giá trị trả về được tuần tự hóa thành JSON bởi thư viện Jackson qua HttpMessageConverter.
  • @RequestBody giải tuần tự JSON thành đối tượng Java; @PathVariable, @RequestParam lấy dữ liệu từ URL.
  • ResponseEntity kiểm soát đầy đủ phản hồi: mã trạng thái, header, thân.
  • Mỗi yêu cầu được xử lý trên một luồng; với Java 21+, bật luồng ảo (spring.threads.virtual.enabled=true) để phục vụ rất nhiều yêu cầu đồng thời mà tốn ít tài nguyên.
  • record rất phù hợp làm DTO (dữ liệu vào/ra API) vì bất biến, ngắn gọn.

API

record SinhVien(String ma, String ten, double diem) {}

@RestController
@RequestMapping("/api/sinhvien")
public class SinhVienController {
    private final Map<String, SinhVien> ds = new ConcurrentHashMap<>();

    @GetMapping
    List<SinhVien> tatCa(@RequestParam(required = false) Double diemToiThieu) {
        return ds.values().stream()
                 .filter(s -> diemToiThieu == null || s.diem() >= diemToiThieu).toList();
    }
    @GetMapping("/{ma}")
    ResponseEntity<SinhVien> mot(@PathVariable String ma) {
        return Optional.ofNullable(ds.get(ma)).map(ResponseEntity::ok)
                       .orElse(ResponseEntity.notFound().build());
    }
    @PostMapping
    ResponseEntity<SinhVien> them(@RequestBody SinhVien sv) {
        ds.put(sv.ma(), sv);
        return ResponseEntity.status(HttpStatus.CREATED).body(sv);
    }
    @DeleteMapping("/{ma}")
    ResponseEntity<Void> xoa(@PathVariable String ma) {
        return ds.remove(ma) != null ? ResponseEntity.noContent().build() : ResponseEntity.notFound().build();
    }
}

Ứng dụng thực tế

Bài toán: API tạo lịch hẹn tư vấn học tập, trả về 201 Created kèm header Location chỉ tới tài nguyên mới theo đúng chuẩn REST:

record LichHen(Long id, String maSv, LocalDateTime thoiGian, String noiDung) {}
record TaoLichHen(String maSv, LocalDateTime thoiGian, String noiDung) {}

@RestController
@RequestMapping("/api/lich-hen")
class LichHenController {
    private final LichHenService svc;
    LichHenController(LichHenService svc) { this.svc = svc; }

    @PostMapping
    ResponseEntity<LichHen> tao(@RequestBody TaoLichHen yc, UriComponentsBuilder uri) {
        LichHen moi = svc.tao(yc);
        return ResponseEntity.created(uri.path("/api/lich-hen/{id}").buildAndExpand(moi.id()).toUri())
                             .body(moi);
    }
}
Thực hành
  1. Hoàn thiện API CRUD lưu trong bộ nhớ.
  2. Thử bằng Postman hoặc tệp .http.
  3. Thêm API thống kê điểm trung bình.
Tóm tắt bài học
  • @RestController trả JSON tự động.
  • Annotation ánh xạ phương thức HTTP.
  • ResponseEntity điều khiển mã trạng thái.