Servlet(二)

Servlet(二),第1张

Servlet(二)

cookie和Session

两个会话跟踪机制

cookie

        //创建cookie
        cookie cookie1=new cookie("name","root");
        cookie cookie2=new cookie("password","123");

        //指定cookie绑定路径
        //路径加上项目名称
        cookie1.setPath(request.getContextPath()+"/xxx/ooo/aaa");
        cookie2.setPath(request.getContextPath()+"/bbbb");
        cookie1.getPath();

        //设置cookie时间 单位为秒
        cookie1.setMaxAge(60*60);
        cookie2.setMaxAge(60*60);

        //添加cookie
        response.addcookie(cookie1);
        response.addcookie(cookie2);

        cookie[] cookies=request.getcookies();
        for (cookie c:cookies){
            System.out.println(c.getName()+" = "+c.getValue());
        }

cookie保存客户端 用来保存数据

客户端有之前保存的数据后 再次访问网页 客户端会将原来保存的cookie一起发送到服务端

进行 *** 作 如 实现免登录

Session

        HttpSession session=request.getSession();
        


        session.setAttribute("name",name);
        
        session.getAttribute("name");

Session是用来保存在服务器端的数据

session可以实现跨servlet的通信 因为session的数据保存在服务器端

作用域问题:

ServletContext、cookie和Session

ServletContext是整个webapp对象

cookie是servlet对象

Session是对话对象 

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5697485.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存