Cookie和Session ----【javaweb-08】
Cookie && Session
1、会话
会话:用户打开一个浏览器,点击了很多超链接,访问多个web资源,关闭浏览器,这个过程可以称之为会话;
有状态的会话:访问过后存在留下的足迹;
2、保存会话的两种形式
1. cookie
2. session
3、Cookie
3.1、什么是cookie
类型为“小型文本文件”,是某些网站为了辨别用户身份;简单理解:cookie,顾名思义是曲奇饼的意思,它的作用是:当你初次访问某网站后,该网站会提供一个cookie给你,证明你的身份,当你再次访问时,则不需要加载信息。
小知识:cookie一般保存在本地的用户目录下的APPdata;
3.2、一个网站的cookie是否存在上限?
1. 一个cookie只能保存一个信息;
2. 一个web站点可以给浏览器发送多个cookie,每个站点最多存放20个cookie;
3. cookie大小有限制:40kb;
4. 浏览器的cookie上限:300个
3.3、有关cookie的常用方法
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
3.4、如何删除cookie
1. 不设置有效期,关闭浏览器,则自动失效;
2. 设置有效时间为0;
3.5、有关cookie的案例
展示上一次访问该网页的时间
代码展示:
package com.charles.cookie; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Date; 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"); Cookie[] cookies = req.getCookies(); if (cookies == null){ Cookie cookie = new Cookie("last", System.currentTimeMillis() + " "); cookie.setMaxAge(60 * 60); resp.addCookie(cookie); resp.getWriter().write("这是您第一次进入这个网站"); }else { for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals("last")){ long lastVisitTime = Long.parseLong(cookies[i].getValue()); Date date = new Date(lastVisitTime); resp.getWriter().write("欢迎光临,您上次访问的时间是:" + date.toLocaleString()); cookies[i].setValue(System.currentTimeMillis() + ""); resp.addCookie(cookies[i]); } } } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
注册servlet,运行后,结果展示:
1. 初次访问
2. 二次访问
4、Session
4.1、什么是session?
Session 译为:会话控制。当浏览器访问网站时,服务器会给每一个浏览器创建一个Session对象;一个Session独占一个浏览器,只要浏览器没有关闭,这个Session就会一直存在。
4.2、Session和Cookie的区别
getId();
getServletContext();
getAttribute();
setAttribute();
removeAttribute();
invalidate();
isNew();
4.4、案例展示
接下来,我将用一个案例来展示这些方法的运用
第一步:创建一个Person实体类
package pojo; public class Person { private String name; private int age; @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Person(String name, int age) { this.name = name; this.age = age; } }
第二步:写一个给Session存读数据的Servlet
package com.charles.session; import pojo.Person; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; public class SessionDemo01 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"); //得到session HttpSession session = req.getSession(); //给session存数据 session.setAttribute("name",new Person("Charles",1)); //获取session的id String id = session.getId(); //判断session是不是新的 if (session.isNew()){ resp.getWriter().write("session创建成功,ID:" + id); } else { resp.getWriter().write("session已经在服务器中存在了,ID:" + id); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
第三步:将存的数据打印在控制台上
package com.charles.session; import pojo.Person; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; public class SessionDemo02 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"); //得到session HttpSession session = req.getSession(); Person name = (Person) session.getAttribute("name"); System.out.println(name.toString()); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
第四步:移出Session并初始化
package com.charles.session; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; public class SessionDemo03 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"); HttpSession session = req.getSession(); session.removeAttribute("name"); session.invalidate(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
第五步:注册Servlet并运行Tomcat
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0" metadata-complete="true"> <servlet> <servlet-name>session</servlet-name> <servlet-class>com.charles.session.SessionDemo01</servlet-class> </servlet> <servlet-mapping> <servlet-name>session</servlet-name> <url-pattern>/s</url-pattern> </servlet-mapping> <servlet> <servlet-name>session02</servlet-name> <servlet-class>com.charles.session.SessionDemo02</servlet-class> </servlet> <servlet-mapping> <servlet-name>session02</servlet-name> <url-pattern>/s2</url-pattern> </servlet-mapping> <servlet> <servlet-name>session03</servlet-name> <servlet-class>com.charles.session.SessionDemo03</servlet-class> </servlet> <servlet-mapping> <servlet-name>session03</servlet-name> <url-pattern>/s3</url-pattern> </servlet-mapping> </web-app>
结果展示:
再次刷新
将页面跳转至/s2后,控制台信息
将页面跳转至/s3后,再次跳转至/s