JavaWeb--Cookie、Session

Cookie、Session

会话

会话:用户打开一个浏览器,点击了很多web资源,访问多个web资源,关闭浏览器,这个过程就叫做会话。

有状态会话:客户端访问服务器,下次在访问服务器,服务器知晓客户端曾今访问过。

一个网站怎么证明用户访问过?

客户端 服务器

  • 服务端给客户端一个cookie,客户端下次访问带上cookie就可以了
  • 服务器通过session登记客户端访问过,下次客户端再次访问,服务器匹配客户端

保存会话的两种技术

cookie(发票)

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

session(登记)

  • 服务器技术:利用这个技术,可以保存用户的会话信息,我们可以把信息或者数据放在Session中

常见场景:

  • 网站登录过后,下次不用登录,第二次访问直接就进去。

  • 从请求中拿到cookie
  • 服务器响应给客户端cookie
// 保存用户上一次访问的时间
public class CookieDemo extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 服务器告诉你 ,你访问的时间,把这个时间封装成一个信件,下次访问的时候,需要带上信件
        req.setCharacterEncoding("gbk");
        resp.setCharacterEncoding("gbk");

        PrintWriter out = resp.getWriter();
        // 服务器端从客户端获取
        Cookie[] cookies = req.getCookies();  // cookie可能存在多个
        // 判断cookie是否存在
        if(cookies!=null){
            //如果存在
            out.write("你上次访问的时间是:");
            for (int i = 0; i <cookies.length ; i++) {
                Cookie cookie = cookies[i];
                // 获取cookie的名字
                if(cookie.getName().equals("lastLoginTime")){

                    long lastLoginTime = Long.parseLong(cookie.getValue());
                    Date date = new Date(lastLoginTime);
                    out.write(date.toLocaleString());
                }
                System.out.println(cookie.getName());
            }
        }else{
            out.write("这是您第一次访问本网站。");
        }
        //服务器给客户端响应一个Cookie
        Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis() + "");
        cookie.setMaxAge(24*60*60);
        resp.addCookie(cookie);

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

image.png
image.png

Session(重点)


image.png

什么是Session:

  • 服务器给每一个用户(浏览器)创建一个Session对象
  • 一个Session独占一个浏览器,只要浏览器没有关闭,这个Session就存在
  • 用户登录之后,整个网站都可以访问!
  • 场景:保存用户的信息,保存购物车信息,在整个网站中经常会使用的数据,我们将它保存在session中

Session和Cookie的区别:

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

使用Session

public class SessionDemo extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 解决乱码问题
        resp.setHeader("content-type","text/html; charset=utf-8");
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        //得到session
        HttpSession session = req.getSession();
        //获取Session的ID
        String sessionId  = session.getId();
        //判断session是否为新创建的
        if(session.isNew()){
            resp.getWriter().write("session 创建成功。session ID:" + sessionId );
        }else{
            resp.getWriter().write("已经在服务器中存在了。session ID:" + sessionId );
        }

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

        //给Session中存字符串
        session.setAttribute("name","shilin.z");
        String name = (String) session.getAttribute("name");
        System.out.println(name);

        //给Session中存用户信息
        session.setAttribute("name",new Person("shilin.z",20));
        Person person = (Person) session.getAttribute("name");
        System.out.println(person.toString());

        //手动注销Session: 刷新,会重新生成sessionID
        //session.removeAttribute("name");
        //session.invalidate();

        //自动注销:在xml中配置
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
<!--    设置Session 默认的失效时间,以分钟为单位-->
<session-config>
<!-- 1分钟后失效 -->
<session-timeout>1</session-timeout>
</session-config>
原文地址:https://www.cnblogs.com/sinlearn/p/13558601.html