首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 程式設計入門

request.getAttribute vs getParameter 深度對比:轉發與鏈接的數據傳遞藝術

     編輯:Java 程式設計入門

核心區別一覽

維度getParameter()getAttribute()
對應設置方法無 setParameter()有 setAttribute()
數據來源HTTP 請求參數(URL 查詢串、表單提交)服務器端設置的請求域屬性
適用場景組件間 鏈接/重定向 傳遞組件間 轉發 共享數據
返回類型StringObject(需強轉)
生命週期隨請求結束隨請求結束(轉發鏈中共享)

場景一:鏈接/表單提交 → getParameter

用戶點擊鏈接或提交表單,瀏覽器發起新請求,參數附在 URL 或請求體中。

JSP 示例

<!-- welcome.jsp -->
<a href="authenticate.jsp?username=qianyunlai.com">登錄</a>
<!-- 或 POST 表單 -->
<form method="post" action="authenticate.jsp">
    用戶名: <input name="username">
    <input type="submit" value="提交">
</form>

<%-- authenticate.jsp --%>
<% String username = request.getParameter("username"); %>
歡迎: <%= username %>

關鍵點:瀏覽器地址欄變化,請求參數隨 HTTP 協議傳輸,getParameter 直接解析請求報文。

場景二:服務端轉發 → getAttribute

<jsp:forward> 或 RequestDispatcher.forward() 實現同一請求內多組件協作,地址欄不變。

轉發鏈數據共享

<%-- authenticate.jsp (轉發源) --%>
<%
    String username = request.getParameter("username"); // 獲取原始參數
    request.setAttribute("username", username);         // 存入請求域
%>
<jsp:forward page="hello.jsp" />

<%-- hello.jsp (轉發目標) --%>
<% String username = (String) request.getAttribute("username"); %>
Hello: <%= username %>

底層機制圖解

鏈接/重定向 (Redirect/Link)          轉發
┌─────────────┐    HTTP請求1    ┌─────────────┐    ┌─────────────┐
│  瀏覽器     │ ─────────────▶ │  組件A      │    │  組件A      │
└─────────────┘  參數在URL/Body  └─────────────┘    │  (同一請求) │
       ▲                                    │        └──────┬──────┘
       │  HTTP請求2 (新請求)                 │  forward()   │
       │  參數在URL/Body                     ▼              ▼
┌─────────────┐                    ┌─────────────┐  ┌─────────────┐
│  瀏覽器     │ ◀──────────────── │  組件B      │  │  組件B      │
└─────────────┘   新響應            └─────────────┘  └─────────────┘
getParameter() 解析請求              setAttribute/getAttribute 共享request域

實戰陷阱與最佳實踐

  1. 類型轉換:getAttribute 返回 Object,必須強轉,建議配合 instanceof 防御
  2. 命名衝突:請求域屬性名建議加前綴(如 attr_userName)避免框架內部屬性衝突
  3. 轉發 vs 重定向選型:
    • 需隱藏業務邏輯、保持請求上下文 → 轉發
    • 需防止表單重複提交、跳轉外部資源 → 重定向
  4. 參數篡改風險:getParameter 來自客戶端,絕不信任,必須校驗/過濾

總結

getParameter 是「讀取客戶端輸入」,getAttribute 是「讀取服務端協作上下文」。搞清請求邊界(新請求 vs 同請求),選型自然清晰。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved