One, four domain object corresponding to object
Domain Objects |
Objects |
Scope |
ServletContext | application | The entire web project, multiple servlet can share data. |
Session | session | Conversation |
Request | Once the request chain | |
PageContext | PageContext | The current page. |
Note: From the top down, the role range from big to small.
Two, cookie and session
1.cookie
Overview:
Cookie, browser technology to save user data.
use:
Create, new Cookie objects on the server side, sent to the browser response.
// 创建 Cookie Cookie cookie3 = new Cookie("username", "jack"); // add more Cookie // cookie3 with the same name as the cookie key // Note: If the key is repeated when the response is more, the last saved browser value. |
Request, the browser cookie will be submitted to the server
// Get an array of cookie System.out.println(cookies);
} |
cookie settings
Time: The default browser cookie is closed, the end of a session disappears by setMaxAge (second) seconds value life time.
// 创建 // set the time
|
Path: The default is the current web application cookie current application generates Cookie, other resources will be submitted access applications.
setPath (path) by setting the path for the cookie screening.
// 设置 cookie // 注意 : 路径写成 绝对路径, /web11 开始 |
删除Cookie
// 创建 Cookie //1. 设置时间为0
|
2.Session
概述 :
Session, 服务器保存用户数据的技术
使用 :
获取session , 依靠request的getSession . Session 对象服务器创建 , 通过 request获取,
当getSession 方法时, 判断请求中,是否有JSESSIONID, 如果没有,必然创建新的session .
如果有JSESSIONID ,通过id查询对应Session ,找到了就返给你, 找不到 创建新的session .
代码演示:
存储数据 // 获取Session // 保存数据 获取数据 // 获取 session // 获取 数据 ,通过 key 获取value System.out.println(username); |
session持久化
依靠cookie生命的延长 , 保证 JSESSIONID 存在 ,所以 可以 关闭浏览器,依然访问Session
session持久化 // 1. 获取 session // 2. 获取 JSESSIONID // 3. 把 id 保存 一个 Cookie中 , 键 名称 必须 JSESSIONID // 4. 设置时间 // 5. response 响应 到浏览器 |
cookie和session区别
cookie |
session |
|
保存位置 |
浏览器 |
服务器 |
数据类型 |
String |
对象 |
安全行 |
不安全 |
安全 |