Servlet:Cookie和Session

本文深入讲解了Cookie与Session的工作原理及应用方式,包括它们如何帮助网站识别用户、区别及各自的使用场景。此外还提供了具体的Java Servlet实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


一、什么是Cookie、Session

1.什么是会话

想要了解Cookie和Session,首先要先了解会话

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

2.一个网站,怎么记录你来过?

  1. 服务端给客户端一个信件,客户端下次访问服务端带上信件就可以了 cookie
  2. 服务端有登记表,你第一次来登记,下次你来的时候我来匹配你; session

3.Cookie和Session

cookie

  • 客户端技术,存放在客户端(一般是appdata下),由服务器发放给用户保存
  • 一个Cookie只能保存一个信息,即一个键值对
  • 一个web站点可以给浏览器发送多个cookie,最多存放20个cookie
  • Cookie大小限制4kb
  • 浏览器上限一共为300个cookie

session

  • 服务端技术,会给每一个用户(浏览器)创建一个Seesion对象,并把信息或者数据放在Session中!(可以存一个对象)
  • 一个Seesion独占一个浏览器,只要浏览器没有关闭,这个Session就存在;

Session和cookie的区别?

  • Cookie是把用户的数据写给用户的浏览器,浏览器保存 (可以保存多个)
  • Session把用户的数据写到用户独占Session中,服务器端保存
    (服务器就保存重要的信息,减少服务器资源的浪费)
图解CookieSession

二、Cookie的具体使用

1.常用方法

Cookie[] cookies = req.getCookies(); //获得Cookie
cookie.getName(); //获得cookie中的key
cookie.getValue(); //获得cookie中的vlaue
new Cookie("lastLoginTime", System.currentTimeMillis()+""); //新建一个cookie
cookie.setMaxAge(24*60*60); //设置cookie的有效期,如果不设置有效期,关闭浏览器自动失效
resp.addCookie(cookie); //响应给客户端一个cookie

2.例子

public class CookieDemo extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        PrintWriter writer = resp.getWriter();
        Cookie[] cookies = req.getCookies();
        if(cookies!=null) {
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                if (cookie.getName().equals("LastLoginTime")) {
                    long l = Long.parseLong(cookie.getValue());
                    Date date = new Date(l);
                    writer.println(date.toLocaleString());
                }
            }
        }
        else{
            writer.println("这是你第一次登录该网站");
        }
        Cookie cookie = new Cookie("LastLoginTime", System.currentTimeMillis() + "");
        cookie.setMaxAge(10); //设置cookie的有效期
        resp.addCookie(cookie); //服务端响应给客户端一个cookie
    }

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

三、Session的具体使用

1.常用方法

public String getId();//获取Sessionid
public ServletContext getServletContext();//获取ServletContext
public Object getAttribute(String name);//获得属性
public void setAttribute(String name, Object value);//添加属性
public void removeAttribute(String name);//移除属性
public void invalidate();//注销
public boolean isNew();//判断是否为新创建

提示:这里的ServletContext相比较于Cookie和Session这样个人的信息来说,是一个共享单位的概念,它之于所有Servlet的顶层。可以理解成是一共

2.具体例子

a.设置session

public class SessionDemo extends HttpServlet {
    @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");

        PrintWriter writer = resp.getWriter();
        HttpSession session = req.getSession();
        //给Session中存东西
        session.setAttribute("user",new Person("Xlaoer",1));

        if(session.isNew()){
            writer.println("Session是新创建的,Sessionid为:"+session.getId());
        }
        else{
            writer.println("Session已经存在来了,Sessionid为"+session.getId());
        }
    }

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

b.获得a中存的东西

public class GetSession extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        Person person = (Person) session.getAttribute("user");
        PrintWriter writer = resp.getWriter();
        writer.println("Name:"+person.getName());
        writer.println("Id:"+person.getId());

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

c.手动清除Session

public class ClearSession extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        session.invalidate();
    }

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

3.web.xml配置session自动过期

<!--设置Session默认的失效时间-->
<session-config>
    <!--15分钟后Session自动失效,以分钟为单位-->
    <session-timeout>15</session-timeout>
</session-config>

etc

  • *如果遇到编码问题,可以考虑使用URLEncoder.encode和RLDecoder.decode方法

  • 可以在Chrome浏览器application下查看cookie和session(如下图)
    在这里插入图片描述

  • (注册session时会发现cookie有个jsessionid:

//Session创建的时候做了什么事情;
        Cookie cookie = new Cookie("JSESSIONID",sessionId);
        resp.addCookie(cookie);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值