首页 > 代码库 > jsp_属性范围_page

jsp_属性范围_page

page属性范围(使用pageContext表示,但是一般习惯于将这种范围称为page范围)表示将一个属性设置在本页上,页面跳转之后无法取得。

下面我们来写两个小例子测试一下:

1.在同一个jsp页面设置一个属性并取出属性:

 1 <%@ page contentType="text/html; charset=utf-8" language="java"     errorPage="" %>
 2 <%@ page import="java.util.*"%>
 3 <!doctype html>
 4 <html>
 5 <head>
 6 <meta charset="utf-8">
 7 <title>page属性范围</title>
 8 </head>
 9 
10 <body>
11     <%
12         pageContext.setAttribute("name","ninic");
13         pageContext.setAttribute("birthday",new Date());
14     %>
15     <%
16         String username=(String)pageContext.getAttribute("name");
17         Date userbirthday=(Date)pageContext.getAttribute("birthday");
18     %>
19     <h2>姓名:<%=username%></h2>
20     <h2>生日:<%=userbirthday%></h2>
21 </body>
22 </html>

浏览器中显示:

技术分享

2.在不同页面设置属性并取出属性

(1)page_demo.jsp

 1 <%@ page contentType="text/html; charset=utf-8" language="java"     errorPage="" %>
 2 <%@ page import="java.util.*"%>
 3 <!doctype html>
 4 <html>
 5 <head>
 6 <meta charset="utf-8">
 7 <title>page属性范围</title>
 8 </head>
 9 
10 <body>
11     <%
12         pageContext.setAttribute("name","ninic");
13         pageContext.setAttribute("birthday",new Date());
14     %>
15     <jsp:forward  page="page_demo2.jsp"/>
16 </body>
17 </html>

(2)page_demo2.jsp

 1 <%@ page contentType="text/html; charset=utf-8" language="java" import="java.util.*" errorPage="" %>
 2 <!doctype html>
 3 <html>
 4 <head>
 5 <meta charset="utf-8">
 6 <title>无标题文档</title>
 7 </head>
 8 
 9 <body>
10      <%
11         String username=(String)pageContext.getAttribute("name");
12         Date userbirthday=(Date)pageContext.getAttribute("birthday");
13     %>
14     <h2>姓名:<%=username%></h2>
15     <h2>生日:<%=userbirthday%></h2>
16 </body>
17 </html>

浏览器中显示:

技术分享

jsp_属性范围_page