1. Xuất dữ liệu dưới dạng File (Download)
Trong các ứng dụng doanh nghiệp, việc trích xuất dữ liệu từ database ra các định dạng như Excel là yêu cầu phổ biến. Dưới đây là cách triển khai một Endpoint để người dùng tải xuống file trực tiếp từ trình duyệt.
@GetMapping("/api/v1/export/excel")
public void exportDataToExcel(HttpServletResponse response) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss");
String timestamp = LocalDateTime.now().format(formatter);
String fileName = "Data_Report_" + timestamp + ".xlsx";
try {
// Thiết lập header cho phản hồi
response.reset();
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
// Sử dụng Try-with-resources để tự động đóng stream
try (OutputStream outputStream = response.getOutputStream()) {
// Giả định workbook là đối tượng tài liệu được tạo từ thư viện như Apache POI
workbook.write(outputStream);
outputStream.flush();
}
} catch (IOException e) {
log.error("Lỗi trong quá trình xuất file: {}", e.getMessage());
} finally {
// Giải phóng tài nguyên workbook nếu cần
if (workbook != null) {
try { workbook.close(); } catch (IOException ignored) {}
}
}
}
Phía Frontend (ví dụ sử dụng JavaScript cơ bản hoặc ExtJS), bạn có thể kích hoạt quá trình tải xuống bằng cách thay đổi địa chỉ cửa sổ:
// Trigger download bằng cách điều hướng window location
function triggerDownload() {
const downloadUrl = "/api/v1/export/excel";
window.location.href = downloadUrl;
}
2. Tiếp nhận File từ Client (Upload)
Để xử lý việc tải lên file, Spring Boot cung cấp interface MultipartFile. Bạn có thể lưu trữ file vào thư mục tạm thời của hệ thống hoặc một đường dẫn chỉ định.
@PostMapping("/api/v1/files/upload")
public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return ResponseEntity.badRequest().body("Vui lòng chọn một file hợp lệ.");
}
try {
String originalName = file.getOriginalFilename();
String extension = originalName.substring(originalName.lastIndexOf("."));
String baseName = originalName.substring(0, originalName.lastIndexOf("."));
// Tạo file tạm trên server
File destination = File.createTempFile(baseName + "_", extension);
file.transferTo(destination);
return ResponseEntity.ok("Tải lên thành công: " + destination.getAbsolutePath());
} catch (IOException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Lỗi khi lưu file.");
}
}
3. Xử lý đa dạng các loại tham số Request
Spring MVC cung cấp nhiều Annotation để ánh xạ dữ liệu từ HTTP Request vào các biến trong Java. Dưới đây là bảng tổng hợp các kỹ thuật phổ biến:
Tham số đường dẫn và truy vấn
- @PathVariable: Lấy giá trị trực tiếp từ URL pattern (ví dụ:
/user/{id}). - @RequestParam: Lấy giá trị từ Query String (ví dụ:
?name=abc).
@GetMapping("/search/{category}")
public ResponseEntity<String> search(
@PathVariable("category") String cat,
@RequestParam(value = "keyword", required = false) String key) {
return ResponseEntity.ok("Category: " + cat + ", Keyword: " + key);
}
Dữ liệu trong Body và Header
- @RequestBody: Chuyển đổi nội dung JSON từ body của request thành một POJO.
- @RequestHeader: Truy cập các giá trị trong HTTP Headers.
- @CookieValue: Đọc dữ liệu từ Cookies được gửi kèm.
@PostMapping("/process")
public void processInfo(
@RequestBody UserDTO user,
@RequestHeader("User-Agent") String agent,
@CookieValue(name = "session_id", defaultValue = "none") String sessionId) {
// Logic xử lý dữ liệu người dùng
}
Sử dụng HttpServletRequest trực tiếp
Trong một số trường hợp cần can thiệp sâu hơn, bạn có thể truyền trực tiếp đối tượng HttpServletRequest vào phương thức của Controller.
@GetMapping("/debug")
public void debugRequest(HttpServletRequest request) {
String authHeader = request.getHeader("Authorization");
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie c : cookies) {
System.out.println(c.getName() + ": " + c.getValue());
}
}
}