cookie,session
1.会话session
用户打开浏览器,点击链接,访问web资源,关闭浏览器,称为一次会话
2.保存会话的技术
cookie:客户端技术,相应请求
session:服务器技术,将信息和数据放在session中
session与cookie的区别:
-
cookie是吧用户的数据写给用户的浏览器,浏览器保存,可以保存多个
-
session是吧用户的数据写给用户独占的session'中,服务器端保存,保存重要的信息,减少服务器资源的浪费
-
session对象由服务器创建
3.cookie
从请求中拿到cookie信息
服务器相应给客户端cookie
-
获得cookie
-
获得cookie的key
-
获得cookie的值
-
新建一个cookie
-
设置cookie的有效期
-
响应给客户端一个cookie
//服务器从客户端获取cookie Cookie[] cookies = req.getCookies(); cookie.getName() cookie.getValue() new Cookie("lastLoginTime", System.currentTimeMillis()+""); cookie.setMaxAge(24*60*60); resp.addCookie(cookie); public class cookieDemo01 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.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]; //获取名字 if (cookie.getName().equals("lastLoginTime")){ //获取cookie中的值 long time = Long.parseLong(cookie.getValue()); Date date = new Date(time); out.write(date.toLocaleString()); } } }else { out.write("first visit"); } //服务器给客户端相应一个cookie Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis()+""); //cookie设置有效期 cookie.setMaxAge(24*60*60); resp.addCookie(cookie); }
3.1 删除cookie
不设置有效期,默认关闭浏览器自动失效
设置有效期为0,同样关闭浏览器失效
4.session
使用场景:
-
保存一个登录用户的信息
-
购物车信息
-
在整个网站中,经常会使用的数据保存在session中
使用方式:
public class sessionDemo01 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setCharacterEncoding("utf-8"); req.setCharacterEncoding("utf-8"); resp.setContentType("text/html;charset=utf-8"); //得到session HttpSession session = req.getSession(); //给session存东西 session.setAttribute("name",new Person("谷子豪",23)); //id String id = session.getId(); //判断session是不是新建的 if (session.isNew()){ resp.getWriter().write("session creat ok,id :"+id); }else { resp.getWriter().write("session have already,id :"+id); } }
注销session:
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = req.getSession(); session.removeAttribute("name"); session.invalidate(); //注销session } <!--设置session的默认失效时间--> <session-config> <!--十五分钟后session自动失效,以分钟为单位--> <session-timeout>15</session-timeout> </session-config>
over
标签:javaweb,resp,req,session,Cookie,cookie,id From: https://www.cnblogs.com/GUGUZIZI/p/17420886.html