Cookie基本應用

在程序里怎么保存用戶的數(shù)據(jù)?
數(shù)據(jù)存在客戶端:cookie
可以用購物車的功能類比。
cookie是客戶端技術,程序把每個用戶的數(shù)據(jù)以cookie的形式寫給用戶各自的瀏覽器。當用戶再去訪問服務器中的web資源時,就會帶著各自的數(shù)據(jù)去。這樣web資源處理的就是用戶各自的數(shù)據(jù)了。

下面寫一個簡單的例子,使用cookie顯示上一次的訪問時間:

//        顯示上一次的訪問時間
private void showLastAccessTime(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.print("您上次訪問的時間是:");

        //獲得用戶的時間cookie
        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());
                SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss");
                Date date = new Date(cookieValue);
                out.print(format.format(date));
            }
        }

        //給用戶返回最新的訪問時間
        Cookie cookie = new Cookie("lastAccessTime",System.currentTimeMillis()+"");
        cookie.setMaxAge(1*30*24*3600);
        cookie.setPath("/cookies");
        response.addCookie(cookie);
    }

Cookie細節(jié):

  1. Cookie是map
  2. web站點可以發(fā)送多個cookie,瀏覽器可存儲多個cookie
  3. 瀏覽器一般可存放300個cookie,每個站點最多存放20個。每個cookie的大小限制為4kb。
  4. 如果創(chuàng)建一個cookie發(fā)送給瀏覽器,默認情況是一個會話級別的cookie,用戶退出瀏覽器后即被刪除。若希望將瀏覽器存儲到硬盤上,需要設置maxAge,并給出一個以秒為單位的時間。設為0,則是刪除該cookie。
  5. 注意,刪除cookie時path必須一致,否則不會刪除。

刪除cookie:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Cookie cookie = new Cookie("lastAccessTime",System.currentTimeMillis()+"");
    cookie.setMaxAge(0);
    cookie.setPath("/cookies");
    response.addCookie(cookie);
    response.sendRedirect("/cookies");
}

下面是一個使用cookie完成購物車的實例:

首頁

/**
 * Created by yun on 2017/5/6.
 * 代表購物車網(wǎng)站首頁
 */
public class CookieDemo1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        //輸出網(wǎng)站所有商品
        out.write("本網(wǎng)站有如下商品:<br/>");
        Map<String, Book> map = DB.getAll();
        for (Map.Entry<String, Book> entry : map.entrySet()) {
            Book book = entry.getValue();
            out.print("<a href='/CookieDemo2?id=" + book.getId() + "' target='_blank'>" + book.getName() + "</a><br/>");
        }


        //顯示用戶曾經(jīng)看到過的商品
        out.write("<br/>"+"您曾經(jīng)看過如下商品有如下商品:<br/>");
        Cookie[] cookies = request.getCookies();
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            if(cookies[i].getName().equals("bookHistory")){
                String[] ids = cookies[i].getValue().split("a"); //轉(zhuǎn)義,是為了防止,和正則表達式中的定義沖突
                for(String id:ids){
                    Book book = (Book) DB.getAll().get(id);
                    out.print(book.getName()+"</br>");
                }
            }
        }
    }
}

class DB {
    private static LinkedHashMap<String,Book> map = new LinkedHashMap();  //鏈表map,方便按序列輸出

    static {
        map.put("1", new Book("1", "heinika的編程之路", "陳利津", "一場有趣的旅程!"));
        map.put("2", new Book("2", "javaweb開發(fā)", "張孝祥", "好書"));
        map.put("3", new Book("3", "全棧工程師之路", "Terry", "全棧??!全棧??!"));
        map.put("4", new Book("4", "shell大全", "陳利津", "一場有趣的旅程!"));
        map.put("5", new Book("5", "heinika的成神之路", "陳利津", "一場有趣的旅程!"));
    }

    public static Map<String,Book> getAll() {
        return map;
    }
}

class Book {
    private String id;
    private String name;
    private String author;
    private String description;

    public Book() {
    }

    public Book(String id, String name, String author, String description) {
        this.id = id;
        this.name = name;
        this.author = author;
        this.description = description;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

}

詳情頁

/**
 * Created by yun on 2017/5/6.
 * 物品詳情頁
 */
public class CookieDemo2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //根據(jù)用戶帶貨來的id,顯示商品的詳細信息
        String id = request.getParameter("id");
        Map<String, Book> map = DB.getAll();
        Book book = map.get(id);
        PrintWriter out = response.getWriter();
        out.print(book.getId() + "<br/>");
        out.print(book.getName() + "<br/>");
        out.print(book.getAuthor() + "<br/>");
        out.print(book.getDescription() + "<br/>");

        //構建cookie,寫回給瀏覽器
        String cookieValue = buildCookie(id, request);
        Cookie cookie = new Cookie("bookHistory", cookieValue);
        cookie.setMaxAge(1 * 30 * 24 * 3600);
        cookie.setPath("/");
        response.addCookie(cookie);
        out.print("<a href='/CookieDemo1'>返回首頁</a>");
    }

    private String buildCookie(String id, HttpServletRequest request) {
        //bookHistory=null          1            1
        //bookHistory=2,1,5         1            1,2,5
        //bookhistory=2,5,4         1            1,2,5
        //bookHistory=2,5           1            1,2,5
        Cookie[] cookies = request.getCookies();
        String bookHistory = null;
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            if (cookies[i].getName().equals("bookHistory")) {
                bookHistory = cookies[i].getValue();
            }
        }

        if (bookHistory == null) {
            return id;
        }

        String[] ids = bookHistory.split("a");
        LinkedList<String> idList = new LinkedList(Arrays.asList(ids));   //為增刪改查提高性能
        if (idList.contains(id)) {
            idList.remove(id);
        } else {
            if (idList.size() == 3) {
                idList.removeLast();
            }
        }
        idList.addFirst(id);
        StringBuffer sb = new StringBuffer();
        for (String bid : idList) {
            sb.append(bid + "a");
        }
        return sb.deleteCharAt(sb.length() - 1).toString();
    }
}
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • HTTP cookie(也稱為web cookie,網(wǎng)絡cookie,瀏覽器cookie或者簡稱cookie)是網(wǎng)...
    留七七閱讀 18,387評論 2 71
  • Spring Cloud為開發(fā)人員提供了快速構建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,694評論 19 139
  • 作者:晚晴幽草軒www.jeffjade.com/2016/10/31/115-summary-of-cookie...
    饑人谷_Dylan閱讀 1,268評論 0 51
  • 背景在HTTP協(xié)議的定義中,采用了一種機制來記錄客戶端和服務器端交互的信息,這種機制被稱為cookie,cooki...
    時芥藍閱讀 2,473評論 1 17
  • Day 18.運用強制力的目的只是為了防衛(wèi),而不是為了懲罰。父母的言行會深深影響孩子,體罰會讓孩子形成武力解決問題...
    慧濤閱讀 233評論 2 0

友情鏈接更多精彩內(nèi)容