request.getParameter(),request.setAttribute()區(qū)別如下:(1)request.getParameter()取得是通過容器的實(shí)現(xiàn)來取得通過類似post,get等方式傳入的數(shù)據(jù),request.setAttribute()和getAttribute()只是在web容器內(nèi)部流轉(zhuǎn),僅僅是請(qǐng)求處理階段。
(2)request.getParameter()方法傳遞的數(shù)據(jù),會(huì)從Web客戶端傳到Web服務(wù)器端,代表HTTP請(qǐng)求數(shù)據(jù)。request.getParameter()方法返回String類型的數(shù)據(jù)。
request.setAttribute()和getAttribute()方法傳遞的數(shù)據(jù)只會(huì)存在于Web容器內(nèi)部
還有一點(diǎn)就是,HttpServletRequest類有setAttribute()方法,而沒有setParameter()方法。拿一個(gè)例子來說一下吧,假如兩個(gè)WEB頁面間為鏈接關(guān)系時(shí),就是說要從1.jsp鏈接到2.jsp時(shí),被鏈接的是2.jsp可以通過getParameter()方法來獲得請(qǐng)求參數(shù).假如1.jsp里有
<form name="form1" method="post" action="2.jsp">請(qǐng)輸入用戶姓名:<input type="text" name="username"><input type="submit" name="Submit" value="提交"></form>的話在2.jsp中通過request.getParameter("username")方法來獲得請(qǐng)求參數(shù)username:
<% String username=request.getParameter("username"); %>
***但是如果兩個(gè)WEB間為轉(zhuǎn)發(fā)關(guān)系時(shí),轉(zhuǎn)發(fā)目的WEB可以用getAttribute()方法來和轉(zhuǎn)發(fā)源WEB共享request范圍內(nèi)的數(shù)據(jù),也還是說一個(gè)例子吧。
有1.jsp和2.jsp1.jsp希望向2.jsp傳遞當(dāng)前的用戶名字,如何傳遞這一數(shù)據(jù)呢?先在1.jsp中調(diào)用如下setAttribute()方法:<%String username=request.getParameter("username");
request.setAttribute("username",username);
%><jsp:forward page="2.jsp" />
在2.jsp中通過getAttribute()方法獲得用戶名字:<% String username=(String)request.getAttribute("username"); %>
本文出自 51CTO.COM技術(shù)博客