栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

【JavaWeb】Session与Cookie详解【附源码】

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【JavaWeb】Session与Cookie详解【附源码】

文章目录
    • 一、cookie
      • 1.什么是cookie?
      • 2.cookie API
      • 3.显示客户上次访问时间
    • 二、Session
      • 1.什么是Session?
      • 2.cookie API
      • 3.显示访问网站的ID
    • 三、cookie和Session区别

一、cookie 1.什么是cookie?

cookie是一种会话技术,它用于将会话过程中的数据保存到客户端的浏览器中,从而使浏览器和服务器可以更好的进行数据交互。

会话:是指一个终端用户与交互系统进行通讯的过程。(百度百科)
有状态会话:浏览器发送的每一次请求,每一个会话都要有唯一的标识来唯一标识自己,当浏览器发送请求的时候就带上这个标识来让服务器识别,从而实现有“状态”的会话。
会话的4个步骤:建立tcp连接—>发出请求文档—>发出响应文档—>释放tcp连接

就是在浏览器访问Web服务器时,服务器会给浏览器发送一些信息,这些信息都保存在cookie中。当浏览器再次访问服务器时,都会在请求头中将cookie发送给服务器,方便服务器对浏览器做出正确的响应。

2.cookie API

Servlet API中提供了javax.servlet.http.cookie类,用于封装cookie信息和提取cookie信息各个属性的setter/getter方法。

3.显示客户上次访问时间
public class cookieServlet01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //只针对POST方式可以防止乱码,而对GET方式无效
//        req.setCharacterEncoding("utf-8");
//        resp.setCharacterEncoding("utf-8");
        //设置浏览器界面的显示编码格式
        resp.setContentType("text/html;charset=utf-8");
        //接收获取全部的来自客户端的cookie,并将这些cookie存放在数组中
        cookie[] cookies = req.getcookies();
        long time;//当前系统时间
        if(cookies!=null){
            resp.getWriter().print("你上次访问是:");
            for(int i=0;i日期,调用parse()方法
                    //格式化:日期—>字符串,调用构造器SimpleDateFormat
                    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:s");
                    time = System.currentTimeMillis();
                    String s2 = sdf1.format(date);
                    resp.getWriter().print(s2);
                    resp.getWriter().print("当前系统时间是:"+sdf1.format(time));
                }
            }
        }else {
            resp.getWriter().print("这是你首次访问");
        }
        cookie cookie = new cookie("lastAccess", System.currentTimeMillis()+"");
        cookie.setMaxAge(1*24*60*60);//设置cookie的时间
        resp.addcookie(cookie);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}

web.xml


    cookieServlet
    com.jd.cookie.cookieServlet01


    cookieServlet
    /cookie

将项目部署到tomcat中,然后运行,若不设置 resp.setContentType(“text/html;charset=utf-8”),则浏览器页面可能乱码如下:

Chrome浏览器具有很强的缓存功能,建议使用别的浏览器访问(此处使用IE),第一次访问:

刷新浏览器,可以看到cookie记录下的上次访问的时间,以及当前系统的时间。

频繁刷新,可以看到上次访问的时间和当前系统时间趋于一致。

二、Session 1.什么是Session?

Session就是一种将会话数据保存到服务端的技术。
Session使用场景:
客户登录信息、购物车信息、在访问网站中经常用到的数据。

2.cookie API

在HttpServletRequest接口中定义了用于获取Session对象的getSession()方法,如下:

HttpSession getSession(boolean var1);
HttpSession getSession();

由于客户端需要接收、记录和回送Session对象的ID,通常情况下,Session是借助cookie技术来传递ID属性的。与Session相关的属性和方法都定义在HttpSession接口中。

HttpSession接口中的常见方法:

3.显示访问网站的ID

(1)显示访问网站的Session的ID

public class SessionServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        //获取session
        HttpSession session = req.getSession();
        //在session中存储信息
        //session.setAttribute("username","小王");//可以存储字符串,也可以存储对象
        session.setAttribute("Person",new Person("小王",19));
        if(session.isNew()){
            resp.getWriter().print("session是新创建的...");
        }else{
            //获取当前的session
            resp.getWriter().print("session已经存在,名称是:"+session.getId());
        }
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

web.xml


    SessionServlet
    com.jd.session.SessionServlet


    SessionServlet
    /s



    
    1

将项目部署到tomcat服务器上,启动服务:首次访问,Session开始被创建

刷新浏览器,发现session已经存在

(2)获取为当前session设置的属性

public class SessionServlet01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //在获取输出流之前调用
        //设置服务器的输出编码位utf-8
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //在获取请求参数之前调用,设置字符集
        req.setCharacterEncoding("utf-8");
        //获取session
        HttpSession session = req.getSession();
        //取出存在session中的信息
        Object person = session.getAttribute("Person");
        //输出到浏览器界面
        resp.getWriter().print(person.toString());
        //输出到控制台
        System.out.println(person.toString());
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}

Person.java

//此处只是为了演示可以为Session设置对象,所以没有设置setter/getter方法
public class Person {
    String name;
    int age;
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + ''' +
                ", age=" + age +
                '}';
    }
}

web.xml


    SessionServlet01
    com.jd.session.SessionServlet01


    SessionServlet01
    /s1

先访问SessionServlet为Session属性赋值,并获取当前的Session的ID

再访问SessionServlet01获取设置的属性

(3)手动清空指定名称的属性

public class SessionServlet02 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        //获取session
        HttpSession session = req.getSession();
        //手动清除session
        session.removeAttribute("Person");
        Person person = (Person) session.getAttribute("Person");
        //再次获取时会找不到,报空指针异常,说明已经清空了sesion设置的属性
        resp.getWriter().print(person.toString());
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}

web.xml


    SessionServlet02
    com.jd.session.SessionServlet02


    SessionServlet02
    /s2

先访问SessionServlet设置属性,然后访问SessionServlet01获取属性

访问SessionServlet02清空设置的属性,看到设置的Session属性已经被清空。

(4)手动注销Session

public class SessionServlet03 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        //获取session
        HttpSession session = req.getSession();
        //手动清除session
        session.removeAttribute("Person");
        //手动注销session
        session.invalidate();
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}

web.xml


    SessionServlet03
    com.jd.session.SessionServlet03


    SessionServlet03
    /s3

访问SessionServlet,频繁刷新,可以看到sesion的名称一分钟内不会变化。

访问SessionServlet03,看到Session已经已经失效。

三、cookie和Session区别

1、session 在服务器端,cookie 在客户端(浏览器)
2、session 默认被存在在服务器的一个文件里(不是内存)
3、session 的运行依赖 session id,而 session id 是存在 cookie 中的,也就是说,如果浏览器禁用了 cookie ,同时 session 也会失效(但是可以通过其它方式实现,比如在 url 中传递 session_id)
4、session 可以放在 文件、数据库、或内存中都可以。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/676376.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号