request.getAttribute()和request.getParameter()兩個方法的區別

來源:互聯網
上載者:User

標籤:post   方式   字元   submit   com   use   多個   傳遞參數   -name   

request.getAttribute()獲得的資料必須曾經有過setAttibute()過;

而request.getParameter()獲得是用戶端POST或者GET請求時所攜帶的參數的值

 

getParameter 是用來接受用post個get方法傳遞過來的參數的.
getAttribute 必須先setAttribute.

(1)request.getParameter() 取得是通過容器的實現來取得通過類似post,get等方式傳入的資料,request.setAttribute()和getAttribute()只是在web容器內部流轉,僅僅是請求處理階段。

(2)request.getParameter() 方法傳遞的資料,會從Web用戶端傳到Web伺服器端,代表HTTP請求資料。request.getParameter()方法返回String類型的資料。

request.setAttribute() 和 getAttribute() 方法傳遞的資料只會存在於Web容器內部

還有一點就是,HttpServletRequest 類有 setAttribute() 方法,而沒有setParameter() 方法。

拿一個例子來說一下吧,假如兩個WEB頁面間為連結關係時,就是說要從1.jsp連結到2.jsp時,被連結的是2.jsp可以通過getParameter()方法來獲得請求參數.

假如1.jsp裡有

Html代碼  
  1. <form name="form1" method="post" action="2.jsp">  
  2. 請輸入使用者姓名:<input type="text" name="username">  
  3. <input type="submit" name="Submit" value="提交">  
  4. </form>  

 

的話在2.jsp中通過request.getParameter("username")方法來獲得請求參數username:

Html代碼  
  1. < % String username=request.getParameter("username"); %>  

 


但是如果兩個WEB間為轉寄關係時,轉寄目的WEB可以用getAttribute()方法來和轉寄源WEB共用request範圍內的資料,也還是說一個例子吧。

有1.jsp和2.jsp

1.jsp希望向2.jsp傳遞當前的使用者名稱字,如何傳遞這一資料呢?先在1.jsp中調用如下setAttribute()方法:

Html代碼  
  1. <%  
  2. String username=request.getParameter("username");  
  3. request.setAttribute("username",username);  
  4. %>  
  5.   
  6. <jsp:forward page="2.jsp" />  

 


在2.jsp中通過getAttribute()方法獲得使用者名稱字:

Html代碼  
  1. <% String username=(String)request.getAttribute("username"); %>  

 

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


(2) 當兩個Web組件之間為連結關係時,被連結的組件通過getParameter()方法來獲得請求參數,


(3) 當兩個Web組件之間為轉寄關係時,轉寄目標組件通過getAttribute()方法來和轉寄源組件共用request範圍內的資料。


一般通過表單和連結傳遞的參數使用getParameter

通過request.setAttribute("name","jerry")的方式賦值的使用request.getAttribute("name")


這個問題主要是request和session的差別,request範圍較小一些,只是一個請求,簡單說就是你在頁面上的一個操作, request.getParameter()就是從上一個頁面中的url、form中擷取參數,但如果一個request涉及多個類,後面還要取參數,可以用request.setAttribute()和request.getAttribute(),但是當結果輸出之後,request就結束了。

而session可以跨越很多頁面,可以理解是用戶端同一個IE視窗發出的多個請求。這之間都可以傳遞參數,比如很多網站的使用者登入都用到了。


一般可以用getParameter得到頁面參數。。。字串。。。

getAttribute()可以得到對象。。。


getParameter可以得到頁面傳來的參數如?id=123之類的。

getAttribute()常用於servlet頁面傳遞參數給jsp

request.getAttribute()和request.getParameter()兩個方法的區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.