java HttpServlet 之 會話Cookie和Session

Cookie技術:將一些參數存入客戶端硬盤中(可以持久化的存入用戶硬盤中)
Session技術:將一些參數存入服務器端(默認關閉瀏覽器就沒了,但是可以進行持久化)


Cookie:

 
        //1.創建Cookie並添加
        //創建Cookie對象 
        Date date=new Date();
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String time = format.format(date);

        //因爲數據裏面有空格 在tomcat高版本直接就報錯 進行特殊處理
        time = URLEncoder.encode(time,"UTF-8");

        Cookie cookie=new Cookie("lastAccessTime",time);
        //設置Cookie的持久化時間(int seconds) //毫秒
        cookie.setMaxAge(5*60*1000); //設置5分鐘  設置0其實就是移除了Cookie
        //設置Cookie攜帶路徑
        cookie.setPath("/"); //訪問服務器所有資源都會攜帶這個 默認不設置是同級的目錄
        //添加進響應
        resp.addCookie(cookie);

        //2.獲取打印所有Cookie
        Cookie[] cookies = req.getCookies();
        if(cookies!=null)
        for (Cookie c:cookies) {
            String name = c.getName();
            //解析特殊處理
            String value = URLDecoder.decode(c.getValue(),"UTF-8");
            resp.getWriter().write(name+":"+value);
            resp.getWriter().write("<br />");
        }
        else
        {
            resp.getWriter().write("沒有Cookie <br />");
        }


Session:

        //存入
        req.getSession().setAttribute(name,val);
        //取出
        req.getSession().getAttribute(name);
Session持久化(關閉瀏覽器還存在):

        HttpSession session=req.getSession();
        String id = session.getId();
        Cookie cookie=new Cookie("JSESSIONID",id);
        cookie.setMaxAge(60*60*1000); // 設置個一小時
        resp.addCookie(cookie);


測試代碼:百度雲盤下載:https://pan.baidu.com/s/1eSAOiP0  密碼:b5zr

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章