Response

Response là phản hồi mà server gửi về client sau khi xử lý xong yêu cầu (request).


🖨️ In thẳng dữ liệu với PrintWriter

// Thiết lập kiểu nội dung phản hồi là HTML
response.setContentType("text/html; charset=UTF-8");

// Lấy đối tượng PrintWriter để ghi dữ liệu phản hồi
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<h1>Hello, world!</h1>");
out.println("</body>");
out.println("</html>");

Một số Content-Type phổ biến:

  • text/html: Trang HTML
  • text/plain: Văn bản thuần túy
  • application/json: Dữ liệu JSON
  • application/xml: Dữ liệu XML

➡️ Chuyển tiếp với RequestDispatcher

// Tạo một đối tượng chuyển tiếp đến một tài nguyên nội bộ (ví dụ: JSP)
RequestDispatcher dispatcher = request.getRequestDispatcher("result.jsp");

// Chuyển yêu cầu hiện tại đến tài nguyên khác
dispatcher.forward(request, response);
  • Không thay đổi URL trên trình duyệt.

↗️ Chuyển hướng với sendRedirect

// chuyển hướng sang một URL khác
response.sendRedirect("login");
  • URL sẽ thay đổi trên trình duyệt. Một request mới sẽ được tạo ra.

📌 So sánh forwardsendRedirect

Tính năngforward()sendRedirect()
Đường dẫn URLKhông thay đổiThay đổi theo URL chuyển hướng
Loại requestNội bộ (server-side)Ngoại vi (client-side)
Truyền dữ liệuTruyền cùng request ban đầuTạo request mới

Các loại response khác

File Download Response

Gửi file nhị phân như PDF, Excel, ảnh… từ server về client để tải về.

response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment;filename=\"file.pdf\"");
OutputStream out = response.getOutputStream();
// Ghi dữ liệu file vào output stream

Image/Media Response

Dùng để trả về hình ảnh, âm thanh hoặc video như một luồng nhị phân (binary stream).

response.setContentType("image/jpeg");
OutputStream out = response.getOutputStream();
// Đọc và ghi ảnh từ server ra output stream

Error Response

Gửi mã lỗi HTTP như 404, 403, 500... để báo lỗi cho trình duyệt.

response.sendError(HttpServletResponse.SC_NOT_FOUND, "Page not found");