1. 程式人生 > >Request的getParameter和getAttribute方法的區別

Request的getParameter和getAttribute方法的區別



HttpServletRequest.getParameter("modelName"); 能取到想要的modelObject嗎?經過測試之後,發現是不能的。後來想想,其他道理挺簡單的,當兩個Web元件之間為轉發關係時,轉發源會將要共享 request範圍內的資料先用setAttribute將資料放入到HttpServletRequest物件中,然後轉發目標通過 getAttribute方法來取得要共享的資料。而MVC中用的就是Web元件之間的轉發啊!

下面整理一下getParameter和getAttribute的區別和各自的使用範圍。

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

(2)當兩個Web元件之間為連結關係時,被連結的元件通過getParameter()方法來獲得請求引數,例如假定welcome.jsp和authenticate.jsp之間為連結關係,welcome.jsp中有以下程式碼:
<a  href="authenticate.jsp?username=wolf">authenticate.jsp </a>
或者:
<form  name="form1" method="post"  action="authenticate.jsp"> 請輸入使用者姓名:<input  type="text" name="username">   <input  type="submit"  name="Submit" value="提交"> </form>
在authenticate.jsp中通過request.getParameter("username")方法來獲得請求引數username:
<%  String  username=request.getParameter("username"); %>

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

假定 authenticate.jsp和hello.jsp之間為轉發關係。authenticate.jsp希望向hello.jsp傳遞當前的使用者名稱字, 如何傳遞這一資料呢?先在authenticate.jsp中呼叫setAttribute()方法:
<% String username=request.getParameter("username"); request.setAttribute("username",username); %>
<jsp:forward page="hello.jsp" />
在hello.jsp中通過getAttribute()方法獲得使用者名稱字:
<% String  username=(String)request.getAttribute("username"); %> Hello: <%=username %>
從更深的層次考慮,request.getParameter()方法傳遞的資料,會從Web客戶端傳到Web伺服器端,代表HTTP請求資料。request.getParameter()方法返回String型別的資料。
request.setAttribute()和getAttribute()方法傳遞的資料只會存在於Web容器內部,在具有轉發關係的Web元件之間共享。這兩個方法能夠設定Object型別的共享資料。
request.getParameter()取得是通過容器的實現來取得通過類似post,get等方式傳入的資料。

request.setAttribute()和getAttribute()只是在web容器內部流轉,僅僅是請求處理階段。

getAttribute是返回物件,getParameter返回字串 總的來說:request.getAttribute()方法返回request範圍內存在的物件,而request.getParameter()方法是獲取http提交過來的資料。