保存会话的两种技术
cookie
- 客户端技术 (响应,请求)req
public class CookieDemo01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//服务器,告诉你,你来的时间,再把时间封装成一个一个信件,你下次带来,我就知道你进来了
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
PrintWriter out = resp.getWriter();
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("lasttime"))
{
//获得cookie的值
Long l = Long.parseLong(cookie.getValue());
Date date = new Date(l);
out.write(date.toLocaleString());
}
}
}else{
out.write("这是你第一次访问本站");
}
//服务器给客户端一个cookie
Cookie cookie = new Cookie("lasttime", System.currentTimeMillis()+"");
resp.addCookie(cookie);
}
cookie设置有效期
cookie.setMaxAge(24*60*60);//一天
Session(重点)
- 服务器技术,利用这个技术,可以保存用户的会话信息 我们可以把信息或者数据放在Session中!
什么事session:
- 服务器会给每一个用户(游览器) 创建一个session对象
- 一个session独占一个游览器,只要游览器没有关闭,这个session就存在
- 用户登录之后,整个网站都可以访问
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("");
//得到session
HttpSession session = req.getSession();
//给session中存东西
session.setAttribute("name","qingjiang");
//获取session的ID
String sessionid = session.getId();
//判断session是不是新创建
if(session.isNew())
{
resp.getWriter().write("session创建成功,id"+sessionid);
}
else
{
resp.getWriter().write("session ID"+sessionid);
}
}
}
session和cookie的区别:
- Cookie是把用户的数据写给用户的浏览器,浏览器保存 (可以保存多个)
- Session把用户的数据写到用户独占Session中,服务器端保存 (保存重要的信息,减少服务器资源的浪费)
- Session对象由服务创建;
使用场景:
- 保存一个登录用户的信息;
- 购物车信息;
- 在整个网站中经常会使用的数据,我们将它保存在Session中;
Session回话自动过期:
<!--设置Session默认的失效时间-->
<session-config>
<!--15分钟后Session自动失效,以分钟为单位-->
<session-timeout>15</session-timeout>
</session-config>