JSP中四種屬性範圍(pageContext,request)

在JSP中提供了四種屬性的保存範圍,所謂的屬性的保存範圍,指的是一個設置的對象,能夠在多少個頁面中保存,並能夠使用。java

四種屬性範圍:瀏覽器

①pageContext:只在一個頁面中保存屬性,跳轉後無效;服務器

②request:只在一次請求中保存屬性,服務器跳轉後依然有效;session

③session:在一次會話範圍中,不管如何跳轉都有效,但新開瀏覽器則無效;app

④application:在整個服務器上保存,全部用戶均可以使用。jsp

屬性操做方法spa

NO 方法
類型
描述
1
public void setAttribute(String name,Object value)
普通 設置屬性的名稱和內容
2 public Object getAttribute(String name)
普通 根據屬性名稱取得內容
3 public removeAttribute(String name) 普通 刪除指定的屬性

四個內置對象都存在以上三個方法。code

設置屬性的時候,屬性的名稱是String,內容是Object。Object能夠設置任意內容對象

一,page範圍(pageContext範圍)---->表示將一個屬性設置在頁面上,跳轉後沒法取得rem

 <body>
	<%
		//設置page屬性範圍,此範圍只能在本頁面起做用
		pageContext.setAttribute("name","IronMan") ;
		pageContext.setAttribute("birthday",new Date()) ;
	%>
	<%
		//從page屬性中取得內容,並執行向下轉型,由於取得後返回的類型是Object,因此必須向下轉型操做
		String username = (String) pageContext.getAttribute("name") ;	//向下轉型,把父類對象當作子類對象,子類有而父類不必定有
		Date userbirthday = (Date) pageContext.getAttribute("birthday") ;
	%>
	<h2>姓名:<%=username %></h2>
	<h2>年齡:<%=userbirthday %></h2>
  </body>

經過<jsp:forward>跳轉,則跳轉以後屬性沒法取得

 <body>
  <%
  		//設置page範圍,此屬性只能在JSP頁面中起做用
  		pageContext.setAttribute("name","IronMan") ;
  		pageContext.setAttribute("birthday",new Date()) ;
  %>
	<jsp:forward page="page_scope_03"></jsp:forward>			<%--服務器端跳轉--%>
	</body>
 <body>
  <% 
  		//從page範圍中取得屬性,由於返回的類型是Object,因此要執行向下轉型
  		String username = (String)pageContext.getAttribute("name") ;
  		Date userbirthday = (Date)pageContext.getAttribute("birtyday") ;
  %>
  <h2><%=username %></h2>
  <h2><%=userbirthday %></h2>
  </body>

    如今發現服務器跳轉以後,發現內容取得,則一個page範圍中的內容只能在一個頁面內保存。

    若是但願服務器跳轉以後能夠繼續取得屬性,則使用更大範圍的跳轉---->request跳轉

二,request屬性範圍

    若是要在服務器跳轉以後,屬性還能夠保存下來,則使用request屬性範圍操做。request屬性範圍表示,在服務器跳轉以後,全部設置的內容依然能夠保存下來。

request_scope_01.jsp

 <body>
		<%
			request.setAttribute("name","IronMan") ;
			request.setAttribute("birthday",new Date()) ;
		%>
		<jsp:forward page="request_scope_02.jsp"></jsp:forward>
  </body>

request_scope_02.jsp

 <body>
		<%
			String username = (String) request.getAttribute("name") ;
			Date userbirthday = (Date) request.getAttribute("birthday") ;
		%>
		<h2>姓名:<%=username %></h2>
		<h2>生日:<%=userbirthday %></h2>
  </body>

    若是跳轉換成超連接跳轉,則沒法取得屬性,由於超連接跳轉後,地址欄信息改變,屬於客戶端跳轉而不是服務器跳轉。是沒法取得屬性的。

<body>
	<%	// 設置request的屬性範圍,此屬性只能在服務器跳轉中有做用
		request.setAttribute("name","SuperMan") ;
		request.setAttribute("birthday",new Date()) ;
	%>
	<!-- 使用超連接跳轉,地址欄改變,屬於客戶端跳轉,而不是服務器跳轉,因此不能取得屬性 -->	
	<a href = "request_scope_02.jsp">經過超連接取得屬性</a>		
  </body>
相關文章
相關標籤/搜索