pageContext和局部变量的区别?
pageContext: 保存的键值仅在本个页面有效。在未来学习Taglib过程当中,将发挥巨大作用。类变量被所有用户(浏览器)只在这一页时共享(例如例1.1),而pageContext 被某个用户(浏览器)只在这一页时才有。pageContext范围比类变量小,和局部变量是一样的,但局部变量可以在非service的方法中用,而 pageContext只能在service方法中用。 见例子2.4
马克- to-win:马克 java社区:防盗版实名手机尾号: 73203。
5)局部变量:转化成servlet后的某个方法中的局部变量。
6)类变量:转化成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就取不出来了。 结果就变成如下了 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);
}
}
输出的结果是:
rmark-to-win amark-to-win smark-to-win
比较pageContext,类变量和局部变量,下面给出一个例子。
例 2.4
<%@ page contentType="text/html; charset=GBK"%>
<html>
<body bgcolor="#ffffff">
<%!double called() {
int c=9;//局部变量可以放在service外的方法里。
/*下一句错误,因为pageContext只能放在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>
输出结果:
4 is still 4
3
xyz
再次刷新访问,无论换不换浏览器,结果都变成:
4 is still 4
4
xyz
再刷:
4 is still 4
5
xyz
再刷:
4 is still 4
6
xyz