1. 程式人生 > >JSP內建物件

JSP內建物件

一、request物件

request物件中封裝了客戶端傳送過來的所有的請求資料

request物件的作用域為一次請求(不能跨頁面訪問)

常用方法:

String getParameter(String name)                  獲取指定名稱的請求引數值(單值)

String[] getParameterValues(String name)     獲取指定名稱的請求引數值(多值)

示例:

<body>        
        第1題:湖北省會是
		<input type="text" name="q1" />
		<br><br>
		第2題:宋朝開國皇帝是
		<br>
		<input type="radio" value="趙匡胤" name="q2">
		趙匡胤
		<input type="radio" value="朱元璋" name="q2">
		朱元璋
		<input type="radio" value="李淵" name="q2">
		李淵
		<br><br>
		第3題:四大名著有
		<br>
		<input type="checkbox" value="紅樓夢" name="q3">
		紅樓夢
		<input type="checkbox" value="水滸傳" name="q3">
		水滸傳
		<input type="checkbox" value="J2EE程式設計技術" name="q3">
		J2EE程式設計技術
		<br><br>
		<button type="submit">提交</button>
</body>
String q1=request.getParameter("q1");
String q2=request.getParameter("q2");
String[] q3=request.getParameterValues("q3");

q1:獲取text內的輸入內容

q2:獲取radio選擇的相關內容

q3陣列:獲取CheckBox選擇的相關內容(CheckBox為多選框,可選多個值)

2、response物件

response物件代表伺服器對客戶端請求的響應

基本用法

response.setHeader()

用法1:設定頁面自動重新整理

response.setHeader("refresh","秒數")

用法2:設定定時跳轉

response.setHeader("refresh","秒數;URL=頁面名稱");

response.sendRedirect()

用法1:請求重定向到新頁面(頁面跳轉)

response.sendRedirect("http://www.baidu.com");

用法2:跳轉時傳送資料

response.sendRedirect("test.jsp?id=1);

String username=request.getParameter("username");
String psd=request.getParameter("psd");
if(check(username,psd)){
	
	out.print("歡迎"+username);
	out.print("<a href='test.jsp'>開始測試</a>");
}
else{
	out.print("登陸失敗,3秒鐘後重新登入");
	response.setHeader("refresh", "3;url='Index.jsp'");
}

該例為一個簡單的登陸檢測頁面,密碼不正確的,3秒鐘後返回主介面

response.sendRedirect("Index.jsp");

該例為立即跳轉到主介面,無需等待

3、session

(1)當一個客戶首次訪問伺服器上頁面時,伺服器將產生一個session物件,同時分配一個String型別的id號

(2)當客戶端再訪問伺服器的其他頁面時,伺服器不再分配給客戶新的session,直到客戶關閉瀏覽器,session物件才被取消

(3)session可以實現在一個會話期間的多頁面間的資料傳遞/共享

基本用法:

session.setAtrribute(String name,Object value)

用value來初始化session物件的某個屬性(name指定,若不存在,則新建一個)的值

session.getAtrribute(String name)

獲取由name指定名稱的session物件屬性的值

方法返回值為object物件

屬性不存在,則返回空

session.setAttribute("username", username);
session.getAttribute("username");

用username初始化username屬性,同時再獲取session物件的username值

4、application物件

(1)web伺服器一旦啟動,就會自動建立一個application物件,並一直保持,知道伺服器關閉

(2)application物件負責提供應用程式在伺服器中執行時的一些全域性資訊,客戶端使用的application物件都是一樣的

(3)在此期間,在任何其他地方對application物件的相關屬性的操作,都將影響到其他使用者對此的訪問

(4)application物件可以實現使用者間資料的共享/傳遞

基本用法:

application.setAttribute(String name,Object value)

用value初始化application物件的某個屬性(name指定,若不存在,則新建一個)的值

application.getAttribute(String name)

獲得由name指定名稱的application物件屬性的值

方法返回值為Object物件

如果屬性不存在,則返回空值

<%
if(session.isNew()){
	if(application.getAttribute("Count")==null){
		application.setAttribute("Count", 1);
	}
	else{
		int number=(Integer)application.getAttribute("Count");
		application.setAttribute("Count", ++number);
	}
}
%>
<p>您是第<%=(Integer)application.getAttribute("Count") %>個使用者。