javaweb学习笔记(四)

本文介绍了如何在Servlet中使用Cookie和Session来管理用户数据。Cookie用于将数据存储在客户端,而Session则将数据存储在服务器端。文章通过示例代码展示了如何读取和设置Cookie,以及检查Session是否新创建。同时,对比了两者在应用场景上的差异,建议在保存用户登录信息、购物车数据等场景中使用Session。
摘要由CSDN通过智能技术生成

cookie

/保存用户上一次访问的时间
public class CookieDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setHeader("Content-Type","text/html;charset=utf-8");

        PrintWriter out = resp.getWriter();

        //cookie,服务端从客户端获取
        Cookie[] cookies = req.getCookies();

        if (cookies != null) {
            out.write("上一次访问");
            for (Cookie cookie : cookies) {
                if("time".equals(cookie.getName())) {
//                    cookie.getValue();
                    Date date = new Date(Long.parseLong(cookie.getValue()));
                    SimpleDateFormat sdf = new SimpleDateFormat();
                    out.write(sdf.format(date));
                }
            }
        } else {
            out.write("第一次访问");
        }
        Cookie cookie = new Cookie("time", System.currentTimeMillis() + "");

        resp.addCookie(cookie);
    }

Session

和cookie区别:

  1. cookie是把用户的数据写给用户的浏览器,浏览器可以保存
  2. session是用户的数据写到用户独占的session中, 服务器端保存
  3. session由服务创建

建议使用场景:

  1. 保存一个用户登录信息
  2. 购物车信息
  3. 在整个网站中经常使用的数据,保存在session中
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决乱码问题
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        //
        HttpSession session = req.getSession();
        //set
        session.setAttribute("name","zzz");

        //get ID
        String id = session.getId();

        //判断是否新创建

        if(session.isNew()) {
            resp.getWriter().write("session创建成功,ID 为" + id);
        }else {
            resp.getWriter().write("session已经存在,ID 为" + id);
        }

    }

得到session

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

        //
        HttpSession session = req.getSession();


        String name =(String) session.getAttribute("name");
        System.out.println("name" + name);

    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值