Cookie和Session学习记录

Cookie 和 Session

会话(Session):

​ 用户打开一个浏览器,点击了许多超链接,访问了多个web资源,关闭浏览器这个过程可以称之为会话。

有状态会话:

​ 记录了上次的访问者。

Cookie :

​ 客户端技术(响应、请求)。

  1. 请求中获取cookie信息
  2. 服务器响应给客户端

记录上次访问时间的页面

public class CookieTest extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从request中获取cookie
        Cookie[] cookies = req.getCookies();

        //设置响应文本类型和编码
        resp.setContentType("text/html;charset=utf-8");

        //初始化数据
        String name = "lastTime";
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time  = sdf.format(date);

        //以utf-8格式对时间字符串进行编码
        time= URLEncoder.encode(time,"utf-8");

        PrintWriter writer = resp.getWriter();
        //如果cookies不为空,则从中取出名称为lastTime的值,并响应到网站页面
        if(cookies!=null){
            for(Cookie cookie : cookies){
                if(cookie.getName().equals(name)) {
                    //将时间字符串以utf-8格式解码,防止乱码
                    writer.println("上次访问时间:" + URLDecoder.decode(cookie.getValue(),"utf-8"));
                }
            }
        }else{
            //cookies为空表示第一次访问网站
            writer.println("第一次访问网站!");
        }
        //更新cookie中的访问时间
        Cookie cookie = new Cookie(name,time);
        //设置cookie最大存在时间(1天)
        cookie.setMaxAge(24*60*60);
        resp.addCookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

Session:

​ 服务器端技术,利用这个这个技术,可以保存用户的会话信息,我们可以把信息或者数据存储在session中。

​ **常见场景:**网站登录以后,下次访问可以不需要再次登录,第二次访问就处于登录状态。一般这种数据将会保存在本地的用户目录下app/data/…下。

什么是Session:

​ 服务器会给每一个用户(浏览器)创建一个session对象

​ 一个session独占一个浏览器,只要浏览器没有关闭,这个session就存在

​ 用户登录后整个网站都能访问,保存用户的信息,保存购物车的信息

利用session存数据

/**
 * @author wj
 * @date 2021/7/9 - 21:57
 */
public class SessionTest extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决乱码
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html");

        //获取session
        HttpSession session = req.getSession();

        //向session中存储数据
        session.setAttribute("person",new person("张三",21));

        //获取sessionId
        String id = session.getId();

        //判断session是否新创建的
        if(session.isNew()){
            resp.getWriter().write("session创建成功!id:"+id);
        }else{
            resp.getWriter().write("session已经存在!id:"+id);
        }
    }
}
/**
 * @author wj
 * @date 2021/7/9 - 22:10
 */
public class SessionDemoTest extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决乱码问题
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html");

        //获取session
        HttpSession session = req.getSession();

        //读取session中的数据并输出
        person person = (person) session.getAttribute("person");
        resp.getWriter().write(person.toString());
    }
}

取出数据:

在这里插入图片描述

Cookie和Session区别:

  1. cookie是将用户数据写到用户浏览器中,浏览器可以保存多个
  2. session是将用户数据写到用户独占的session中,服务器端保存(保存重要的信息,减少服务器资源的浪费)
  3. session对象是由服务器创建

工作流程

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值