ทั้งสองใช้สำหรับนำทางไปหน้าอื่น แต่ทำงานต่างกันอย่างสิ้นเชิง
| ลักษณะ | <jsp:forward> | response.sendRedirect() |
|---|---|---|
| กลไก | Server-side forward (ภายใน container) | Client-side redirect (HTTP 302) |
| Request object | ส่งต่อ request object เดียวกัน (attributes คงอยู่) | Browser สร้าง request ใหม่ (attributes หาย) |
| URL ใน browser | ไม่เปลี่ยน (ยังคง URL เดิม) | เปลี่ยนเป็น URL ใหม่ |
| ขอบเขต | ใน webapp เดียวกัน (same context) | ไปได้ทุก URL (ข้าม domain/context ได้) |
| ประสิทธิภาพ | เร็วกว่า (1 request) | ช้ากว่า (2 requests: redirect + new request) |
| Bookmark/Refresh | Refresh = forward ซ้ำ (อาจ double submit) | Refresh = request ใหม่ไป URL ใหม่ (ปลอดภัยกว่า) |
รูปแบบโค้ด
<jsp:forward>
<jsp:forward page="/anotherPage.jsp" />
<!-- หรือพร้อมพารามิเตอร์ -->
<jsp:forward page="/anotherPage.jsp">
<jsp:param name="param1" value="value1" />
</jsp:forward>
response.sendRedirect()
response.sendRedirect("https://example.com/otherPage.jsp");
<!-- หรือ relative -->
response.sendRedirect("otherPage.jsp");
แนวทางเลือกใช้
- Forward: การประมวลผลภายในเดียวกัน (controller → view, chaining)
- Redirect: หลัง POST (PRG pattern), เปลี่ยน domain, ต้องการ URL ใหม่ใน address bar
ความแตกต่างหลัก: forward เป็น server-side (request เดียว attributes คงอยู่ URL ไม่เปลี่ยน) redirect เป็น client-side HTTP 302 (request ใหม่ attributes หาย URL เปลี่ยน)