1. 程式人生 > >http請求中Parameter(引數) 和Attribute(屬性)的區別

http請求中Parameter(引數) 和Attribute(屬性)的區別

HttpServletRequest類既有getAttribute()方法,也由getParameter()方法,這兩個方法有以下區別:

(1)HttpServletRequest類有setAttribute()方法,而沒有setParameter()方法

(2)當兩個Web元件之間為連結關係時,被連結的元件通過getParameter()方法來獲得請求引數,例如假定welcome.jsp和authenticate.jsp之間為連結關係,welcome.jsp中有以下程式碼:
  1. <ahref="authenticate.jsp username=weiqin">authenticate.jsp a>

或者:
  1. <form name="form1" method="post" action="authenticate.jsp"
    >  
  2. 請輸入使用者姓名:<input type="text" name="username"><input type="submit" name="Submit" value="提交">
  3. </form>  
在authenticate.jsp中通過request.getParameter("username")方法來獲得請求引數username: 
  1. <% String username=request.getParameter("username"); %>

(3)當兩個Web元件之間為轉發關係時,轉發目標元件通過getAttribute()方法來和轉發源元件共享request範圍內的資料。假定authenticate.jsp和hello.jsp之間為轉發關係。authenticate.jsp希望向hello.jsp傳遞當前的使用者名稱字,如何傳遞這一資料呢?先在authenticate.jsp中呼叫setAttribute()方法:
在hello.jsp中通過getAttribute()方法獲得使用者名稱字:Hello: 

(4)從更深的層次考慮,request.getParameter()方法傳遞的資料,會從Web客戶端傳到Web伺服器端,代表HTTP請求資料。request.getParameter()方法返回String型別的資料。

request.setAttribute()和getAttribute()方法傳遞的資料只會存在於Web容器內部,在具有轉發關係的Web元件之間共享。這兩個方法能夠設定Object型別的共享資料。

getParameter得到的都是String型別的。或者是http://a.jsp id=123中的123,或者是某個表單提交過去的資料。
getAttribute則可以是物件。
getParameter()是獲取POST/GET傳遞的引數值;
getAttribute()是獲取物件容器中的資料值;
getParameter:用於客戶端重定向時,即點選了連結或提交按扭時傳值用,即用於在用表單或url重定向傳值時接收資料用。
getAttribute:用於伺服器端重定向時,即在sevlet中使用了forward函式,或struts中使用了mapping.findForward。getAttribute只能收到程式用setAttribute傳過來的值。
另外,可以用setAttribute,getAttribute傳送接收物件.而getParameter顯然只能傳字串。
setAttribute是應用伺服器把這個物件放在該頁面所對應的一塊記憶體中去,當你的頁面伺服器重定向到另一個頁面時,應用伺服器會把這塊記憶體拷貝另一個頁面所對應的記憶體中。這樣getAttribute就能取得你所設下的值,當然這種方法可以傳物件。session也一樣,只是物件在記憶體中的生命週期不一樣而已。
getParameter只是應用伺服器在分析你送上來的request頁面的文字時,取得你設在表單或url重定向時的值。