jsp_属性范围_page

时间:2023-12-18 10:57:26

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

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

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

 <%@ page contentType="text/html; charset=utf-8" language="java"     errorPage="" %>
<%@ page import="java.util.*"%>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>page属性范围</title>
</head> <body>
<%
pageContext.setAttribute("name","ninic");
pageContext.setAttribute("birthday",new Date());
%>
<%
String username=(String)pageContext.getAttribute("name");
Date userbirthday=(Date)pageContext.getAttribute("birthday");
%>
<h2>姓名:<%=username%></h2>
<h2>生日:<%=userbirthday%></h2>
</body>
</html>

浏览器中显示:

jsp_属性范围_page

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

(1)page_demo.jsp

 <%@ page contentType="text/html; charset=utf-8" language="java"     errorPage="" %>
<%@ page import="java.util.*"%>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>page属性范围</title>
</head> <body>
<%
pageContext.setAttribute("name","ninic");
pageContext.setAttribute("birthday",new Date());
%>
<jsp:forward page="page_demo2.jsp"/>
</body>
</html>

(2)page_demo2.jsp

 <%@ page contentType="text/html; charset=utf-8" language="java" import="java.util.*" errorPage="" %>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head> <body>
<%
String username=(String)pageContext.getAttribute("name");
Date userbirthday=(Date)pageContext.getAttribute("birthday");
%>
<h2>姓名:<%=username%></h2>
<h2>生日:<%=userbirthday%></h2>
</body>
</html>

浏览器中显示:

jsp_属性范围_page

注:pageContext有一种设置属性的方法:

public void setAttribute(String name,Object value,int scope)  //这个方法可以设置属性并指定保存范围。

public static final int PAGE_SCOPE   //page属性范围

public static final int REQUEST_SCOPE  //request属性范围

public static final int SESSION_SCOPE //session 属性范围

public static final int APPLICATION_SCOPE //application属性范围