天天看點

jsp四個域對象的作用範圍

jsp的内置對象:

内置對象是在JSP頁面中無需建立就可以直接使用的變量。在JSP中一共有9個這樣的對象!它們分别是:

l  out(JspWriter);

l  config(ServletConfig);

l  page(目前JSP的真身類型);

l  pageContext(PageContext);

l  exception(Throwable);

l  request(HttpServletRequest);

l  response(HttpServletResponse);

l  application(ServletContext);

l  Session     (HttpSession)。

--------------------------------------------------------------------

pageContext對象

    作用域:目前頁面,隻能在目前通路頁面使用或擷取屬性

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>" target="_blank" rel="external nofollow" >
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css" target="_blank" rel="external nofollow" >
	-->
  </head>
  
  <body>
	<!-- 設定屬性 -->
	<% 	pageContext.setAttribute("name", "englishTeacher"); 
		pageContext.setAttribute("birthday", new Date());
	%>
	
	<!-- 擷取屬性 -->
	<%
		String name = (String)pageContext.getAttribute("name");
		Date birthday = (Date) pageContext.getAttribute("birthday");
	%>	
	<!-- 列印屬性 -->
	<%=name %>
	<%=birthday %>
  </body>
</html>
           

request作用域:

在目前請求範圍内有效,伺服器跳轉也算同一次請求,同樣有效

代碼:

<body>
	<!-- 設定屬性 -->
	<% 	request.setAttribute("name", "englishTeacher"); 
		request.setAttribute("birthday", new Date());
	%>
	
	<!-- 擷取屬性 -->
	<%
		String name = (String)request.getAttribute("name");
		Date birthday = (Date) request.getAttribute("birthday");
	%>	
	<!-- 列印屬性 -->
	<h1><%=name %></h1>
	<h1><%=birthday %></h1>
	<!-- 跳轉代碼 -->
	<jsp:forward page="/success.jsp"></jsp:forward>
  </body>
           

跳轉之後的success.jsp的代碼:

<body>
	
	<!-- 擷取屬性 -->
	<%
		String name = (String)request.getAttribute("name");
		Date birthday = (Date) request.getAttribute("birthday");
	%>	
	<!-- 列印屬性 -->
	<h1><%=name %></h1>
	<h1><%=birthday %></h1>
	<h2>success.jsp</h2>
	
  </body>
           

session對象作用域:

在一次會話中有效,既:隻要浏覽器視窗不關閉 就能擷取到session

即使一個浏覽器開多個代碼都可以,但是一旦浏覽器關閉就over....

代碼同上:略

application作用域

生命周期随同伺服器的開閉。。。既在整個伺服器的運作期,。

隻要伺服器開着,就可以擷取到

代碼:略  同上

jsp