session和cookie
http协议是无状态的协议,客户端请求到服务端,数据交互完成后即断开了连接,而不是一直处于连接状态。
(例如:网络异常断开后,网页并没有立即显示断开连接,而是在刷新之后才显示断开连接)
这就意味着服务端无法一直连接、跟踪客户端
(A用户在购物车中添加了一件商品后,过了一会又添加了一件商品。服务端由于不能一直跟踪客户,不知道第二次添加的商品的是A 或者是B或是其他人)
由此引入了cookie和session
(cookie和session就像是一个用户的身份证,可以唯一标识是哪个用户。在添加商品时,拿出身份证,服务端就知道是哪个客户在购物车中添加了商品)
session(会话)
百度定义:指一个终端用户与交互系统进行通信的时间间隔,通常指从注册进入系统到注销退出系统之间所经过的时间。
例如:用户登陆了淘宝,访问了许多商品网页,最后退出淘宝的一整个过程,称为一次会话。
客户端访问服务端时,服务端把客户端的信息记录在服务器上,这些信息就是session
demo1–共享数据等
session可以传递对象等,cookie只能传递一些文本信息
public class SessionServlet1 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");
//新建一个session
HttpSession session = req.getSession();
session.setAttribute("name","张三");
Person person = new Person();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd");
Date date = null;
try {
date = dateFormat.parse("2000-10-01");
} catch (ParseException e) {
e.printStackTrace();
}
session.setAttribute("person",new Person("李四",20,date));
//获取sessionID
String id = session.getId();
//
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 {
super.doPost(req, resp);
}
}
获取数据
public class SessionGet 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");
//
HttpSession session = req.getSession();
String name = (String) session.getAttribute("name");
resp.getWriter().write(name);
Person person = (Person) session.getAttribute("person");
resp.getWriter().write(person.toString());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
注销session
相当于关闭浏览器
手动注销
public class SessionInva extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
//清除key = name 的session
session.removeAttribute("name");
//手动注销session
session.invalidate();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
在web.xml中设置自动注销
<session-config>
<!--以分钟为单位,session失效时间-->
<session-timeout>1</session-timeout>
</session-config>
Cookie
服务端给客户端(用户)一个”文本“ ,客户端之后访问服务端时带上这个文本,服务端就知道是谁来访问了,从而做出相应的响应。
cookie只能存放一些文本信息。
demo1–获取上次访问的时间:
//cookie获取上次访问的时间
public class CookieServlet 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");
PrintWriter out = resp.getWriter();
//获取cookies
Cookie[] cookies = req.getCookies();
if(cookies!=null)
{
out.write("上次访问时间是:");
for (int i = 0; i < cookies.length; i++) {
//如果cookie是上次登陆时创建的cookie,则获取cookie的值,并以日期的方式输出
if (cookies[i].getName().equals("lastLoginTime"))
{
long l = Long.parseLong(cookies[i].getValue());
Date date = new Date(l);
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String format = dateFormat.format(date);
System.out.println(format);
out.write(format);
}
}
}else {
out.write("第一次访问此网页");
}
/*
Date date = new Date(System.currentTimeMillis());
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String format = dateFormat.format(date);
System.out.println(format);
*/
Cookie cookie = new Cookie("lastLoginTime",System.currentTimeMillis()+"");
//设置cookie有效时长 单位秒
cookie.setMaxAge(60*60);
resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
demo2–删除cookie
public class CookieServlet2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie = new Cookie("lastLoginTime",System.currentTimeMillis()+"");
//设置cookie有效时间为0秒,即删除cookie
cookie.setMaxAge(0);
resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
demo3–不能直接存取中文时的解决办法(不限定于cookie)
//cookie中存取中文
public class CookieServlet3 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");
//cookie不能直接放中文时需要转码
//Cookie cookie = new Cookie("name", URLEncoder.encode("张三","utf-8"));
Cookie cookie = new Cookie("name", URLEncoder.encode("张三","utf-8"));
resp.addCookie(cookie);
PrintWriter out = resp.getWriter();
//当不能直接得到中文时需要转码 解码
//out.write(URLDecoder.decode(cookie.getValue(),"utf-8"));
out.write(cookie.getValue());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
cookie和session的区别
cookie 由客户端创建,保存在客户端浏览器上(用户的浏览器上);
session由服务端创建,保存在服务器上
如果说cookie是通过检查用户的身份证来确定客户身份的话,那么session就是通过检查服务器上的用户登记表来确定客户身份
session可以存放对象等复杂数据类型,cookie只能存放一些小的文本信息
session一般在关闭浏览器后就失效了,cookie可以设置有效时间或者永久有效