會話技術介紹-cookie

##會話技術介紹 ###什麼是會話技術 會話能夠簡單理解爲:用戶開一個瀏覽器,點擊多個超連接,訪問服務器多個web資源而後關閉瀏覽器,整個過程稱之爲一個會話。 ###會話過程要解決的一些問題 每一個用戶與服務器進行交互的過程當中,各自會有一些數據,程序要想辦法保存每一個用戶的數據, 例如:用戶點擊點擊超連接經過一個servlet購買一個商品,程序應該保存用戶購買的產品,以便於用戶點結帳時,結帳servlet能夠獲得用戶商品爲用戶結帳。 question:用戶購買的商品保存在request或servletContext行不行 answer:不行 ##保存會話數據的兩種技術 cookie是客戶端技術, 程序把每一個用戶的數據,以cookie的形式寫給用戶各自的瀏覽器,當瀏覽器再去訪問服務器中的web資源時,就會帶着各自的數據去,這樣,web資源處理的就是用戶各自的數據了。html

session是服務端技術
利用這個技術,服務器在運行時能夠爲每個用戶的瀏覽器建立一個其獨享的session對象,因爲session是用戶瀏覽器對象,因此用戶在訪問服務器的web資源時,能夠把各自的數據放在各自的session中,當用戶再去訪問服務器中的其它web資源時,其它資源再從用戶各自的session中取出數據爲用戶服務。

##cookie案例 ###cookie api javax.servlet.http.cookie類用戶建立一個cookie,response接口中也定義了一個addCookie方法,它用於在其響應頭中增長一個相應的set-cookie頭字段。一樣,request接口中也定義了一個getCookies方法,它用於獲取客戶提交的cookie。 cookie類的方法:java

  1. public Cookie(String name,String value)
  2. setValue , getValue
  3. setMaxAge , getMaxAge
  4. setPath, getPath
  5. setDomain,getDomain
  6. getName

生成cookie的代碼web

Cookie cookie = new Cookie("lastAccessTime",System.currentTimeMillis());
cookie.setMaxAge(10);
cookie.setPath("/day07");
response.addCookie(cookie);

刪除cookie cookie.setMaxAge(0); 用js也能夠刪除Cookie ##顯示用戶上次訪問的時間api

response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter pw = response.getWriter();
        pw.print("你上次的訪問時間是:");
        Cookie cookies[] = request.getCookies();
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            if (cookies[i].getName().equals("lastAccessTime")) {
                long cookieValue = Long.parseLong(cookies[i].getValue());
                Date date = new Date(cookieValue);
                pw.print(date.toLocaleString());
            }
        }

        Cookie cookie = new Cookie("lastAccessTime", System.currentTimeMillis() + "");
        cookie.setMaxAge(120);
        cookie.setPath(request.getContextPath());
        response.addCookie(cookie);

##cookie的細節瀏覽器

*. 一個cookie職能標識一種信息,它至少含有一個標識該信息的名稱(name)和值(value)服務器

*. 一個web站點能夠給一個web瀏覽器發送多個Cookie,一個WEB瀏覽器也能夠存儲多個web站點提供的cookie。cookie

*. 瀏覽器通常只容許存放300個cookie,每一個站點最多存放20個cookie,每一個cookie的大小限制爲4KB。session

*. 若是建立一個cookie,並將他發送到瀏覽器,默認狀況下它是一個會話級別的cookie(存儲在瀏覽器的內存中),用戶推出瀏覽器以後即被刪除。若但願瀏覽器將該cookie存儲在磁盤上,則須要使用setMaxAge,並給出一個以秒爲單位的時間。將最大實效設爲0則是命令瀏覽器刪除該cookie。app

*. 刪除cookie時,path必須一致,不然不會刪除。網站

##cookie案例:顯示用戶瀏覽歷史紀錄

需求說明

public class ViewallServlet extends HttpServlet {
 response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.write("本網站有以下商品: </br>");
        Map<Integer, Book> map = Db.getAll();
        Set<Entry<Integer, Book>> entrySet = map.entrySet();
        for (Entry<Integer, Book> entry : entrySet) {
            Book book = entry.getValue();
            out.print("<a href=/test-web/BuybookServlet?id=" + entry.getKey() + ">" + book.getName() + "</a><br/>");
        }
        
        // 顯示用戶曾經看過的商品
        Cookie[] cookies = request.getCookies();
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            if (cookie.getName().equals("bookHistory")) {
                String value = cookie.getValue();
                if (value == null) {
                    return;
                }
                System.out.println(value);
                String[] ids = value.split(",");
                for (String id : ids) {
                    out.print("瀏覽過的商品</br>");
                    out.print(Db.getAll().get(Integer.valueOf(id)).getName() + "</br>");
                }
            }
        }
}
public class BuybookServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        Book book = Db.getAll().get(Integer.valueOf(id));
        PrintWriter pw = response.getWriter();
        pw.print(book.getId() + "</br>" + book.getName());
        // 構建cookie,回寫瀏覽器
        String cookieValue = buildCookie(id, request);
        Cookie cookie = new Cookie("bookHistory", cookieValue);
        cookie.setMaxAge(600);
        cookie.setPath(request.getContextPath());
        response.addCookie(cookie);
    }

    private String buildCookie(String id, HttpServletRequest request) {
        String bookHistory = null;
        Cookie cookies[] = request.getCookies();
        if (cookies == null) {
            return id;
        }
        for (Cookie cook : cookies) {
            if (cook.getName().equals("bookHistory")) {
                bookHistory = cook.getValue();
                break;
            }
        }
        if (bookHistory == null) {
            return id;
        }
        LinkedList<String> list = new LinkedList<String>();
        String[] splits = bookHistory.split("\\,");
        for (String split : splits) {
            list.addFirst(split);
        }

        if (list.isEmpty()) {
            return id;
        }

        if (list.contains(id)) {
            list.remove(id);
            list.addFirst(id);
        } else {
            if (list.size() > 3) {
                list.removeLast();
                list.addFirst(id);
            } else {
                list.addFirst(id);
            }
        }
        StringBuffer buffer = new StringBuffer();
        for (String bid : list) {
            buffer.append(bid).append(",");
        }
        buffer.deleteCharAt(buffer.length()-1);
        return buffer.toString();
    }
}
相關文章
相關標籤/搜索