日期:2014-05-16  浏览次数:20387 次

JSP四种范围对象的作用域

作用域范围从小到大顺序:

pageContext----request----session----application

?

其中:

pageContext:

作用域仅限于当前页面对象,可以近似于理解为java的this对象,离开当前JSP页面(无论是redirect还是forward),则pageContext中的所有属性值就会丢失。

request:

作用域是同一个请求之内,在页面跳转时,如果通过forward方式跳转,则forward目标页面仍然可以拿到request中的属性值。如果通过redirect方式进行页面跳转,由于redirect相当于重新发出的请求,此种场景下,request中的属性值会丢失。

session:

session的作用域是在一个会话的生命周期内,会话失效,则session中的数据也随之丢失。

application:

作用域是最大的,只要服务器不停止,则application对象就一直存在,并且为所有会话所共享。

?

关于pageContext的示例:

page1.jsp

<%@ page language="java" contentType="text/html; charset=GBK"  pageEncoding="GBK"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<title>Insert title here</title>

</head>
<body>
<%

request.setAttribute("username","张三");
pageContext.setAttribute("username","张三");

System.out.println("request.getAtrribute()="+request.getAttribute("username"));
System.out.println("pageContext.getAtrribute()="+pageContext.getAttribute("username"));

System.out.println("页面跳转");
request.getRequestDispatcher("page2.jsp").forward(request,response);

%>
</body>
</html>

?

page2.jsp

<%@ page language="java" contentType="text/html; charset=GBK"  pageEncoding="GBK"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<title>Insert title here</title>

</head>
<body>
<%

System.out.println("request.getAtrribute()="+request.getAttribute("username"));
System.out.println("pageContext.getAtrribute()="+pageContext.getAttribute("username"));

%>
</body>
</html>

?

输出结果:


?

http://huangqiqing123.iteye.com/blog/1435186

1 楼 feijing 2012-03-02  
好文章,ok