| 維度 | getParameter() | getAttribute() |
|---|---|---|
| 對應設置方法 | 無 setParameter() | 有 setAttribute() |
| 數據來源 | HTTP 請求參數(URL 查詢串、表單提交) | 服務器端設置的請求域屬性 |
| 適用場景 | 組件間 鏈接/重定向 傳遞 | 組件間 轉發 共享數據 |
| 返回類型 | String | Object(需強轉) |
| 生命週期 | 隨請求結束 | 隨請求結束(轉發鏈中共享) |
用戶點擊鏈接或提交表單,瀏覽器發起新請求,參數附在 URL 或請求體中。
<!-- 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 直接解析請求報文。
<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域
getAttribute 返回 Object,必須強轉,建議配合 instanceof 防御attr_userName)避免框架內部屬性衝突getParameter 來自客戶端,絕不信任,必須校驗/過濾getParameter 是「讀取客戶端輸入」,getAttribute 是「讀取服務端協作上下文」。搞清請求邊界(新請求 vs 同請求),選型自然清晰。