Cookie & Session

HTTP是无状态协议,也就是没有记忆力,每个请求之间无法共享数据.

Cookie是客户端技术,程序把每个用户的数据以cookie的形式写给用户各自的浏览器.
当用户使用浏览器再去访问服务器中的 web资源时,就会带着各自的数据去.
这样,web资源处理的就是用户各自的数据了.

1.Cookie 是谁来创建,怎么创建的?
服务器端程序来创建:
Cookie cookie = new Cookie(String name,String value);
参数: name: 给共享的数据起一个唯一的标志
value: 要存入的用户的数据
Cookie c = new Cookie(“currentName”,”xiaoming”);

2.如何响应 Cookie 给 浏览器.
response对象.addCookie(Cookie cookie);
resp.addCookie(c);

3.如何获取 Cookie 中的数据.
浏览器带过来的数据理应在请求对象中.
Cookie[] cookies = request对象.getCookies();
遍历数组拼配一个name是currentName 的数据.
cookie.getName() : 获取Cookie 中的唯一标志的名称
cookie.getValue(): 当前Cookie 的数据.

4.修改Cookie
方式一: 再创建一个同 name 值的Cookie 对象来做覆盖的操作:
Cookie cookie = new Cookie(“currentName”,”小明”)
方式二: 直接重新给Cookie赋值
cookie.setValue(“新的数据”)
注意: 两种方式都需要重新响应给浏览器去覆盖之前的Cookie

5.Cookie的中文问题
URLEncoder : 把中文转为非中文的字符串
URLDecoder : 把非中文的字符串转回中文

6 Cookie的分类 :
会话Cookie: 浏览器关闭 Cookie 就失效.
持久Cookie: Cookie 可以保留一定的时间.
cookie.setMaxAge(int value):
使用的秒为单位:
负数: -1 : 不保存Cookie (会话Coookie);
0: 删除Cookie
正数: 设置存活的时间(秒)

Session

Session是服务器端技术,利用这个技术,服务器在运行时可以为每一个用户的浏览器创建一个其独享的session对象,由于session为用户浏览器独享.所以用户在访问服务器的web资源时,可以把各自的数据放在各自的session中,当用户再去访问服务器中的其它web资源时,其它web资源再从用户各自的session中取出数据为用户服务.

Session的使用

Session 的使用:
1 创建或获取Session 对象
HttpSession request.getSession(true) : 获取HttpSession对象,如果存在直接返回,如果不存在,创建一个新的Session对象然后返回.
HttpSession request.getSession(false) : 获取HttpSession对象,如果存在直接返回,如果不存在返回null
HttpSession request.getSession() : 同 1

2 设置共享数据
session.setAttribute(String name,Object value);
参数: name : 共享的数据的唯一标志
value : 要设置的共享数据

3 获取共享数据
session.getAttribute(String name);

4 移除 Session 中的数据
1:删除Session中指定属性名的值.
session.removeAttribute(String name);
2:销毁Session对象
session对象.invalidate();

5 Session的超时管理.
默认的超时时间: 30分钟 : 在Tomcat/conf/web.xml
session.setMaxInactiveInterval(int seconds)

6 URL重写:
Session 是一个特殊的Cookic ,存在浏览器上,用户可选择不接受Cookie
方式一: 使用参数形式 jsessionid 传递给下一个请求,使用 ; 来设置参数的值
方式二: 调用方法来生成带有 jsessionid 的 url
String url = resp.encodeURL(“/session/content”);
开发中不要拒收Cookie