web前後臺數據互動的四種方式(轉)
1.利用cookie物件
Cookie是伺服器儲存在客戶端中的一小段資料資訊。使用Cookie有一個前提,就是客戶端瀏覽器允許使用Cookie並對此做出相應的設定。一般不贊成使用Cookie。
(1)後臺程式碼
1 2 |
|
(2)前臺程式碼
1 2 3 4 5 6 |
|
2.利用session物件
session物件表示特定會話session的使用者資料。客戶第一次訪問支援session的JSP網頁,伺服器會建立一個session物件記錄客戶的資訊。當客戶訪問同一網站的不同網頁時,仍處於同一個session中。
(1)後臺程式碼
1 2 3 |
|
(2)前臺程式碼(jsp頁面)
1 |
|
3.利用request重定向,設定setAttribute
(1)後臺程式碼
1 2 |
|
PS:如果後臺使用的轉發程式碼為 response.sendRedirect("welcome.jsp"); //網址變為welcome.jsp
則request設定的引數無效,因為已經切換到另一個請求了,request引數的有效期為本次請求。
(2)前臺程式碼
1 |
|
4.利用Ajax進行非同步資料請求(得到的資料可以以json或xml格式返回,便於處理)
(1)後臺程式碼案例(運用servlet傳輸資料)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
|
2.前臺js請求處理資料程式碼
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
|
總結:在使用者訪問網站整個生命週期中都會用到的資料用session來儲存,例如使用者名稱,登入狀態,購物車資訊
顯示在網頁上的資訊資料大多通過 request或Ajax方式獲取