jsp request.getParameter() 和request.getAttribute()方法區(qū)別詳解
getParameter 是用來接受用post個get方法傳遞過來的參數(shù)的.
getAttribute 必須先setAttribute.
(1)request.getParameter() 取得是通過容器的實現(xiàn)來取得通過類似post,get等方式傳入的數(shù)據(jù),request.setAttribute()和getAttribute()只是在web容器內(nèi)部流轉(zhuǎn),僅僅是請求處理階段。
(2)request.getParameter() 方法傳遞的數(shù)據(jù),會從Web客戶端傳到Web服務器端,代表HTTP請求數(shù)據(jù)。request.getParameter()方法返回String類型的數(shù)據(jù)。
request.setAttribute() 和 getAttribute() 方法傳遞的數(shù)據(jù)只會存在于Web容器內(nèi)部
還有一點就是,HttpServletRequest 類有 setAttribute() 方法,而沒有setParameter() 方法。
拿一個例子來說一下吧,假如兩個WEB頁面間為鏈接關系時,就是說要從1.jsp鏈接到2.jsp時,被鏈接的是2.jsp可以通過getParameter()方法來獲得請求參數(shù).
假如1.jsp里有
Html代碼
<form name="form1" method="post" action="2.jsp"> 請輸入用戶姓名:<input type="text" name="username"> <input type="submit" name="Submit" value="提交"> </form>
的話在2.jsp中通過request.getParameter("username")方法來獲得請求參數(shù)username:
Html代碼
< % String username=request.getParameter("username"); %>
但是如果兩個WEB間為轉(zhuǎn)發(fā)關系時,轉(zhuǎn)發(fā)目的WEB可以用getAttribute()方法來和轉(zhuǎn)發(fā)源WEB共享request范圍內(nèi)的數(shù)據(jù),也還是說一個例子吧。
有1.jsp和2.jsp
1.jsp希望向2.jsp傳遞當前的用戶名字,如何傳遞這一數(shù)據(jù)呢?先在1.jsp中調(diào)用如下setAttribute()方法:
Html代碼
<% String username=request.getParameter("username"); request.setAttribute("username",username); %> <jsp:forward page="2.jsp" />
在2.jsp中通過getAttribute()方法獲得用戶名字:
Html代碼
<% String username=(String)request.getAttribute("username"); %>
- HttpServletRequest 類有setAttribute()方法,而沒有setParameter()方法
- 當兩個Web組件之間為鏈接關系時,被鏈接的組件通過getParameter()方法來獲得請求參數(shù),
- 當兩個Web組件之間為轉(zhuǎn)發(fā)關系時,轉(zhuǎn)發(fā)目標組件通過getAttribute()方法來和轉(zhuǎn)發(fā)源組件共享request范圍內(nèi)的數(shù)據(jù)。
一般通過表單和鏈接傳遞的參數(shù)使用getParameter
通過request.setAttribute("name","jerry")的方式賦值的使用request.getAttribute("name")
這個問題主要是request和session的差別,request范圍較小一些,只是一個請求,簡單說就是你在頁面上的一個操作, request.getParameter()就是從上一個頁面中的url、form中獲取參數(shù),但如果一個request涉及多個類,后面還要取參數(shù), 可以用request.setAttribute()和request.getAttribute(),但是當結(jié)果輸出之后,request就結(jié)束了。
而session可以跨越很多頁面,可以理解是客戶端同一個IE窗口發(fā)出的多個請求。這之間都可以傳遞參數(shù),比如很多網(wǎng)站的用戶登錄都用到了。
一般可以用getParameter得到頁面參數(shù)。。。字符串。。。
getAttribute()可以得到對象。。。
getParameter可以得到頁面?zhèn)鱽淼膮?shù)如?id=123之類的。
getAttribute()常用于servlet頁面?zhèn)鬟f參數(shù)給jsp
到此這篇關于jsp request.getParameter() 和request.getAttribute()方法區(qū)別詳解的文章就介紹到這了,更多相關jsp request.getParameter() 和request.getAttribute()方法區(qū)別內(nèi)容請搜索以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持!