java學習筆記—會話(24)

來源:互聯網
上載者:User

標籤:

 1 使用Cookie實現顯示使用者的上次訪問時間

public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {         // 頁面輸出         response.setCharacterEncoding("utf-8");         response.setContentType("text/html;charset=utf-8");         request.setCharacterEncoding("utf-8");         // 擷取字元輸出資料流對象         PrintWriter out = response.getWriter();         // 擷取Cookie數組對象         Cookie [] cookies = request.getCookies();         // 定義一個時間的字串變數         String date = null;         // 定義一個變數儲存系統當前日期         Date current_date = new Date();         SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");         // 判斷是否是第一次登陸         if(cookies != null){             // 直接迴圈             for(Cookie cookie : cookies){                 // 擷取Cookie                 if("lasttime".equals(cookie.getName())){                     // 擷取上次訪問的時間                     date = cookie.getValue();                      break;                 }else{                     // 擷取系統時間                     date = format.format(current_date);                 }             }         }else{             // 擷取系統時間             date = format.format(current_date);         }         // 顯示時間         out.println(date);         // 將這次訪問的時間寫入Cookie         Cookie new_cookie = new Cookie("lasttime",format.format(new Date()));          new_cookie.setMaxAge(5*60);         new_cookie.setPath("/day08/showtime");         // 發送         response.addCookie(new_cookie);    }
Cookie細節
  1. 一個Cookie只能儲存一種資訊。
  2. 一個網站可以發送多個Cookie,瀏覽器可以同時攜帶多個Cookie。
  3. 同一個網站最多發送20個Cookie,瀏覽器最多儲存300個Cookie,一個Cookie最多儲存資料在4K以內。
  4. 如果建立了Cookie對象沒有指定最大有效時間那麼不會儲存在瀏覽器的緩衝中。
Session技術

在上面使用Cookie技術儲存會話資訊的時候發現Cookie儲存的資料有限,而且每次需要用戶端瀏覽器攜帶資料,導致網路的負載過大。因此如果需要儲存相對大量的資料,那麼可以直接將資料存放區在伺服器端,這樣可以提高資料的訪問速度。

HttpSession技術就是將會話的資料存放區在伺服器端,便於開發人員直接進行訪問。

1 HttpSession介面

該介面主要定義了一種區分不同使用者並通過request對象擷取該對象的執行個體儲存與使用者相關的資訊的方式。

該介面的對象是tomcat伺服器協助開發人員建立出來的,當開發人員調用request.getSession()方法擷取該介面的對象。

2  常用API

擷取HttpSession對象

HttpSession getSession()                 ? 如果有直接返回,如果沒有直接建立並返回HttpSession getSession(boolean create)        ? true同上,false有返回,沒有null

操作資料

void setAttribute(String name, Object value)     ? 設定指定名的屬性值 Object getAttribute(String name)                 ? 擷取指定名的屬性值Enumeration getAttributeNames()                ? 擷取所有屬性名稱的集合迭代器void removeAttribute(String name)            ? 刪除指定名的屬性

額外的方法

String getId()                             ? 擷取Session的ID值boolean isNew()                         ? 判斷Session是否是新的long getCreationTime()                     ? 擷取Session建立時間的longlong getLastAccessedTime()                 ? 擷取最後一次訪問Session的時間void invalidate()                        ? 指定Session無效

3 HttpSession的讀和寫

1. 寫Session資料

public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {       // 擷取session對象       HttpSession session = request.getSession();       // 放置資料       session.setAttribute("name", "jack");    }

發現響應資訊中以Set-Cookie: JSESSIONID=8AA06CD311EC6A38805C73C93B8FCE4F; Path=/day08回應標頭資料將HttpSession對象的ID值以Cookie的方式發送給瀏覽器進行儲存。

2. 讀Session資料

    public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {       // 擷取Session對象       HttpSession session = request.getSession();       // 取Session資料       String name = (String) session.getAttribute("name");       // 輸出資訊       System.out.println(name);}

請求訊息中使用Cookie: JSESSIONID=8AA06CD311EC6A38805C73C93B8FCE4F攜帶了HttpSession對象的ID值,那麼伺服器根據該值找到對應的HttpSession對象擷取其中的值。

總結:

HttpSession技術底層需要藉助Cookie儲存伺服器端為每一個使用者建立的HttpSession對象的ID值,便於後面拿到該值擷取伺服器指定對象中值。

3 重新審視以上代碼

可以將擷取資料的servlet中的擷取sessiond的代碼修改如下

HttpSession session = request.getSession(false);

現在實際的瀏覽器在啟動多個同一個瀏覽器視窗,那麼自動使用同一個Session對象。一旦Session的有效時間超過了半個小時那麼Session自動銷毀。

4 其他的常用方法

public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {    // 擷取session對象    HttpSession session = request.getSession();    // 調用常用的方法    System.out.println("getId(): "+session.getId());    System.out.println("getLastAccessedTime(): "+session.getLastAccessedTime());    System.out.println("isNew(): "+session.isNew());    System.out.println("getCreationTime(): "+session.getCreationTime());}

運行結果

getId(): F8A7BC23A0B403CE30A69F8B5F903D6AgetLastAccessedTime(): 1358385915203isNew(): truegetCreationTime(): 1358385915203

如果在以上的代碼中使用了  session.invalidate();後繼續往session中添加資料,那麼伺服器報錯

java.lang.IllegalStateException: setAttribute: Session already invalidated

總結:

登陸功能分析à 1. 擷取使用者資料 2. 校正資料 3. 成功,在Session中儲存使用者登陸的標識

登出功能分析à 1. 清除Session中的使用者標識資訊  2. 重新導向到登陸頁面

java學習筆記—會話(24)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.