Response
Response là phản hồi mà server gửi về client sau khi xử lý xong yêu cầu (request).
PrintWriter
🖨️ In thẳng dữ liệu với // 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 HTMLtext/plain
: Văn bản thuần túyapplication/json
: Dữ liệu JSONapplication/xml
: Dữ liệu XML
RequestDispatcher
➡️ Chuyển tiếp với // 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.
sendRedirect
↗️ Chuyển hướng với // 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.
forward
và sendRedirect
📌 So sánh Tính năng | forward() | sendRedirect() |
---|---|---|
Đường dẫn URL | Không thay đổi | Thay đổi theo URL chuyển hướng |
Loại request | Nội bộ (server-side) | Ngoại vi (client-side) |
Truyền dữ liệu | Truyền cùng request ban đầu | Tạ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");