Cookie、Session
1、会话
**会话:**用户打开了一个浏览器,点击了很多超链接,访问多个 web 资源,关闭浏览器,这个过程可以称之为会话。
有状态会话:
一个网站,怎么证明你来过?
客户端 服务端
-
服务端给客户端一个信件,客户端下次访问服务端带上信件就可以了;cookie
-
服务器登记你来过了,下次你来的时候我来匹配你;session
2、保存会话的两种技术
cookie
- 客户端技术(响应,请求)
session
- 服务器技术,利用这个技术,可以保存用户的会话信息。我们可以把信息或者数据放在session中!
常见运用:网站登录之后,下次不用再登录,第二次访问直接就上去了!
3、Cookie
- 从请求中拿到cookie信息
- 服务器响应给客户端
@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 out = resp.getWriter();
// Cookie,服务器从客户端获取
Cookie[] cookies = req.getCookies();
// 判断cookie是否存在
if (cookies != null) {
// 如果存在
out.write("您上一次访问的时间为:");
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
// 获取cookie的名字
if (cookie.getName().equals("lastLoginTime")) {
// 获取cookie中的值
long lastLoginTime = Long.parseLong(cookie.getValue());
Date date = new Date(lastLoginTime);
out.write(date.toLocaleString());
}
}
}else {
out.write("这是您第一次访问本网站");
}
// 服务器给客户端响应一个cookie
Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis() + "");
// 设置cookie的有效期
cookie.setMaxAge(24 * 60 * 60);
resp.addCookie(cookie);
}
细节:
- 一个Cookie只能保存一个信息
- 一个web站点可以给浏览器发送多个cookie,最多存放20个cookie
- Cookie大小有限制4kb
- 浏览器上限300个cookie
删除:
- 不设置有效期,关闭浏览器,自动失效
- 设置有效期时间为0
// 删除cookie
// 首先创建一个cookie,且必须与要删除的一致
Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis() + "");
// 设置cookie的有效期为0,立马生效
cookie.setMaxAge(0);
resp.addCookie(cookie);
如果是中文,需要编码解码:
// 如果是中文,需要编码
Cookie cookie01 = new Cookie("name", URLEncoder.encode("张三"));
// 如果是中文,需要解码
if (cookie.getName().equals("name")) {
out.write(URLDecoder.decode(cookie.getValue(), "utf-8"));
}
4、Session(重点)
什么是session:
-
服务器会给每一个用户(浏览器)创建一个Session对象;
-
一个Session独占一个浏览器,只要浏览器没有关闭,这个Session就存在;
-
用户登陆后,整个网站它都可以访问:保存用户的信息,保存购物车的信息……
Session和Cookie的区别:
- Cookie是把用户的数据写给用户的浏览器,浏览器保存(可以保存多个);
- Session把用户的数据写到用户独占的Session中,服务器保存(保存重要信息,减少服务器资源的浪费);
- Session由服务器创建;
使用场景:
- 保存一个登录用户的信息;
- 购物车信息;
- 在整个网站中经常会使用的数据,我们将它保存在Session中;
使用Session:
@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("张三", 20));
// 获取session的id
String sessionId = session.getId();
// 判断session是不是新创建的
if (session.isNew()) {
resp.getWriter().write("这是一个新创建的session,ID:" + sessionId);
}else {
resp.getWriter().write("服务器已经存在的session,ID:" + sessionId);
}
}
@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 person = (Person) session.getAttribute("name");
resp.getWriter().write(person.toString());
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();// 获取
session.removeAttribute("name");// 移除"name"对应的内容
session.invalidate();// 注销
}
会话自动过期:在web.xml中设置
<session-config>
<!--设置session的默认失效时间,单位是分钟-->
<session-timeout>10</session-timeout>
</session-config>