JavaWeb入门三之Cookie&Session-创新互联

一、Cookie&Session 一、Cookie
  • 存储在浏览器
一、存储数据
// 创建Cookie
// 1.创建Cookie对象
Cookie cookie = new Cookie("username", "张三");
// 2.设置Cookie存活时间,正数为存活时间,负数(默认)为关闭浏览器销毁,0则表示删除此Cookie
// 存活一周,7天
cookie.setMaxAge(60*60*24*7);
// 3.发送Cookie
resp.addCookie(cookie);
二、获取数据
// 获取Cookie
// 1.获取Cookie数组
Cookie[] cookies = req.getCookies();
// 2.遍历数组
for (Cookie cookie : cookies) {// 3.获取数据
    String name = cookie.getName();
    if ("username".equals(name)) {String value = cookie.getValue();
        System.out.println(name + "-" + value);
        break;
    }
}
三、存活时间
cookie.setMaxAge(60*60*24*7);
二、Session
  • 存储在服务器
一、存储数据
// 存储Session
// 1.获取Session对象
HttpSession httpSession = req.getSession();
// 2.存储数据
httpSession.setAttribute("username", "王五");
二、获取数据
// 获取Session
// 1.获取Session对象
HttpSession httpSession = req.getSession();
// 2.获取数据
Object username = httpSession.getAttribute("username");
System.out.println(username);
三、删除数据
// 删除Session中的数据
HttpSession httpSession2 = req.getSession();
httpSession2.removeAttribute("username");
四、销毁
httpSession.invalidate();
五、存活时间
session.setMaxInactiveInterval(60);  // 此处单位是秒
100// 单位是分钟

你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧

作为一家“创意+整合+营销”的成都网站建设机构,我们在业内良好的客户口碑。创新互联公司提供从前期的网站品牌分析策划、网站设计、成都网站制作、网站设计、创意表现、网页制作、系统开发以及后续网站营销运营等一系列服务,帮助企业打造创新的互联网品牌经营模式与有效的网络营销方法,创造更大的价值。
新闻名称:JavaWeb入门三之Cookie&Session-创新互联
本文网址:http://pwwzsj.com/article/djdhpc.html