四种范围对象
四种对象 | 范围 |
---|---|
pageContext | jsp页面容器 (page对象)当前页面有效(页面跳转后无效) |
request | 请求对象 同一次请求有效(请求转发有效,重定向后无效) |
session | 会话对象 同一次会话有效(无论怎么跳转,都有效。跳转/关闭浏览器无效) |
application | 全局对象 全局有效(切换浏览器都有效) |
以上4个对象共有的方法
序号 | 方法&概念 |
---|---|
1 | public Object getAttribute(String name) 返回对象中与指定名称绑定的对象,如果不存在则返回null |
2 | void setAttribute(String name, object obj) :使用指定的名称和值来产生一个对象并绑定到session中 |
3 | void removeAttribute (String name): 根据属性名,删除对象 |
验证:pageContext范围
pagecontext.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
pageContext.setAttribute("hello", "world");
//演示页面跳转后无效
// request.getRequestDispatcher("DemoIfScopeValid.jsp").forward(request,response);
%>
<%=pageContext.getAttribute("hello")//pageContext对象范围只在当前页面有效(页面跳转后无效)
%>
</body>
</html>
结果:
注释去掉,在添加一个配置文件
pagecontext.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
pageContext.setAttribute("hello", "world");
//演示页面跳转后无效
request.getRequestDispatcher("DemoIfScopeValid.jsp").forward(request,response);
%>
<%=pageContext.getAttribute("hello")//pageContext对象范围只在当前页面有效(页面跳转后无效)
%>
</body>
</html>
DemoIfScopeValid.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%=pageContext.getAttribute("hello")
%>
</body>
</html>
结果
验证:request范围
request.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
request.setAttribute("hello", "world");
//验证 同一次请求有效(请求转发有效,重定向后无效)
// request.getRequestDispatcher("DemoIfScopeValid.jsp").forward(request,response);
response.sendRedirect("DemoIfScopeValid.jsp");
%>
<%=request.getAttribute("hello")
%>
</body>
</html>
DemoIfScopeValid.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%=request.getAttribute("hello")
%>
</body>
</html>
利用:重定向转发输出的结果是null,理由重定向请求次数为2。