了解JSP中request屬性的用法
一、request.getParameter() 和request.getAttribute() 區(qū)別
1.request.getParameter()取得是通過容器的實(shí)現(xiàn)來取得通過類似post,get等方式傳入的數(shù)據(jù),request.setAttribute()和getAttribute()只是在web容器內(nèi)部流轉(zhuǎn),僅僅是請求處理階段。
2.request.getParameter()方法傳遞的數(shù)據(jù),會(huì)從Web客戶端傳到Web服務(wù)器端,代表HTTP請求數(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()方法來獲得請求參數(shù).
假如1.JSP里有
- <form name="form1" method="post" action="2.jsp">
- 請輸入用戶姓名:<input type="text" name="username">
- <input type="submit" name="Submit" value="提交">
- < SPAN>form>
的話在2.JSP中通過request.getParameter("username")方法來獲得請求參數(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.JSP
1.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"); %>
二、request.getAttribute()與request.setAttribute()
request.getAttribute("nameOfObj")可得到JSP頁面一表單中控件的Value。其實(shí)表單控件中的Object的 name與value是存放在一個(gè)哈希表中的,所以在這里給出Object的name會(huì)到哈希表中找出對應(yīng)它的value。
而不同頁面間傳值使用request.setAttribute(position, nameOfObj)時(shí),只會(huì)從a.JSP到b.JSP一次傳遞,之后這個(gè)request就會(huì)失去它的作用范圍,再傳就要再設(shè)一個(gè) request.setAttribute()。而使用session.setAttribute()會(huì)在一個(gè)過程中始終保有這個(gè)值。
P.S.:JavaScript與JSP中不能相互傳值,因?yàn)镴avaScript運(yùn)行在客戶端,而JSP運(yùn)行在服務(wù)器端。若想使它們之間可以相互傳遞參數(shù),可以在JSP中設(shè)置一個(gè)hidden控件,用它的value結(jié)合上面所說的用法來傳遞所需的數(shù)值。
【編輯推薦】