pageContext和局部變量的區(qū)別?
pageContext: 保存的鍵值僅在本個(gè)頁面有效。在未來學(xué)習(xí)Taglib過程當(dāng)中,將發(fā)揮巨大作用。類變量被所有用戶(瀏覽器)只在這一頁時(shí)共享(例如例1.1),而pageContext 被某個(gè)用戶(瀏覽器)只在這一頁時(shí)才有。pageContext范圍比類變量小,和局部變量是一樣的,但局部變量可以在非service的方法中用,而 pageContext只能在service方法中用。 見例子2.4
馬克- to-win:馬克 java社區(qū):防盜版實(shí)名手機(jī)尾號: 73203。
5)局部變量:轉(zhuǎn)化成servlet后的某個(gè)方法中的局部變量。
6)類變量:轉(zhuǎn)化成servlet后的類變量。
例 2.3
<%@ page contentType="text/html; charset=GBK" %>
<html>
<body>
<%
request.setAttribute("rName","rmark-to-win");
application.setAttribute("aName","amark-to-win");
session.setAttribute("sName","smark-to-win");
request.getRequestDispatcher("/Cookie/AddCookie").forward(request,response);
/*如用下面的response,request就取不出來了。 結(jié)果就變成如下了 null amark-to-win smark-to-win*/
// response.sendRedirect("http://localhost:8080/ServletHello/Cookie/AddCookie");
%>
</body>
</html>
package com;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AddCookie extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String rav=(String)request.getAttribute("rName");
String scs=(String)this.getServletContext().getAttribute("aName");
String sa=(String)request.getSession().getAttribute("sName");
System.out.println(rav+" "+scs+" "+sa);
}
}
輸出的結(jié)果是:
rmark-to-win amark-to-win smark-to-win
比較pageContext,類變量和局部變量,下面給出一個(gè)例子。
例 2.4
<%@ page contentType="text/html; charset=GBK"%>
<html>
<body bgcolor="#ffffff">
<%!double called() {
int c=9;//局部變量可以放在service外的方法里。
/*下一句錯(cuò)誤,因?yàn)閜ageContext只能放在service里面,外面can not be resolved.*/
// pageContext.getAttribute("abc");
return Math.random();
}%>
<%!int a = 3;%>
<%
int b=4;
if (pageContext.getAttribute("abc") != null) {
pageContext.setAttribute("abc", "xyz1");
} else {
pageContext.setAttribute("abc", "xyz");
}
%>
<%
if(b==4) System.out.println(b+" is still 4");
b++;
System.out.println(a++);
/*you can not write System.out.println(abc); it will report error by drawing the red line*/
System.out.println(pageContext.getAttribute("abc"));
%>
<h1>JBuilder Generated JSP</h1>
</body>
</html>
輸出結(jié)果:
4 is still 4
3
xyz
再次刷新訪問,無論換不換瀏覽器,結(jié)果都變成:
4 is still 4
4
xyz
再刷:
4 is still 4
5
xyz
再刷:
4 is still 4
6
xyz