Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม

การใช้งาน <c:redirect> tag ใน JSP

Tag <c:redirect> ทำ redirect (HTTP 302) พร้อม URL rewriting อัตโนมัติ รองรับ context-relative URLs และ <c:param>

Attributes

AttributeคำอธิบายRequiredDefault
urlURL ปลายทางYes-
context/context-name สำหรับ webapp อื่นNoCurrent app

ตัวอย่าง

<%@ taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core" %>
<html>
<head><title>Redirect Example</title></head>
<body>
    <c:redirect url="https://www.example.com"/>
</body>
</html>

จะ redirect ไป https://www.example.com

ร่วมกับ <c:param>

<c:redirect url="/search">
    <c:param name="q" value="java"/>
    <c:param name="lang" value="th"/>
</c:redirect>

→ /myapp/search?q=java&lang=th;jsessionid=...

เปรียบเทียบ

คุณสมบัติ<c:redirect>response.sendRedirect()
URL RewritingอัตโนมัติManual (encodeRedirectURL)
Parameters<c:param> nestedManual string concat
Context-relativeรองรับ context attrManual
SyntaxDeclarative (XML-like)Scriptlet

ข้อควรระวัง

  • <c:redirect> ต้องอยู่ก่อนเนื้อหาอื่นใน response (เหมือน sendRedirect)
  • หลัง redirect code ต่อไปจะไม่รัน (throw IllegalStateException ถ้าพยายามเขียน response)
  • ใช้ใน JSP ที่เป็น controller/logic เท่านั้น ไม่ใช่ view template