cookie机制
在浏览器地址栏输入javascript:alert(document.cookie)查看网站cookie
记录用户访问次数
- java中把Cookie封装成javax.servlet.http.Cookie类。
- 每个Cookie都是Cookie类的对象。
- 服务端通过Cookie类对象对客服端进行操作。
- 通过request.getCookie()获取客服端提交的所有Cookie(以Cookie[]数组形式返回)。
- 通过response.addCookie(Cookie cookie)向客服端设置Cookie。
- Cookie对象使用key-value属性对的形式保存用户状态,一个Cookie对象保存一个属性对,一个request和response同时使用多个Cookie。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33request.setCharacterEncoding("UTF-8");
String username = "";
int visitTimes = 0;
// 所有的 cookie
Cookie[] cookies = request.getCookies();
// 遍历所有的 Cookie 寻找 用户帐号信息与登录次数信息
for(int i=0; cookies!=null&&i<cookies.length; i++){
Cookie cookie = cookies[i];
out.print(cookie.getName());
out.print(":");
out.print(cookie.getValue());
out.print("<br>");
if("username".equals(cookie.getName())){
username = cookie.getValue();
}
else if("visitTimes".equals(cookie.getName())){
visitTimes = Integer.parseInt(cookie.getValue());
cookie.setValue("" + ++visitTimes);
}
}
// 如果没有找到 Cookie 中保存的用户名,则转到登录界面
if(username == null || username.trim().equals("")){
throw new Exception("您还没有登录。请先登录");
}
// 修改 Cookie,更新用户的访问次数
Cookie visitTimesCookie = new Cookie("visitTimes", Integer.toString(++visitTimes));
response.addCookie(visitTimesCookie);
Cookie不可跨域名
Unicode编码保存中文
编码使用java.net.URLEncoder类的encode(String str , String encoding)方法,解码使用java.net.URLDecoder类的decode(String str , String encoding)。
服务端:1
2
3
4
5
6
7// 使用中文的 Cookie. name 与 value 都使用 UTF-8 编码.
Cookie cookie = new Cookie(
URLEncoder.encode("姓名", "UTF-8"),
URLEncoder.encode("刘京华", "UTF-8"));
// 发送到客户端
response.addCookie(cookie);
客户端:1
2
3
4
5
6
7
8
9
10
11
12
13if(request.getCookies() != null){
for(Cookie cc : request.getCookies()){
String cookieName = URLDecoder.decode(cc.getName(), "UTF-8");
String cookieValue = URLDecoder.decode(cc.getValue(), "UTF-8");
out.println(cookieName + "=");
out.println(cookieValue + "; <br/>");
}
}
else{
out.println("Cookie 已经写入客户端. 请刷新页面. ");
}
Base64编码:保存二进制图片
Cookie不仅可以使用ASCII与Unicode编码,还能使用二进制数据。
读取图片
1 | File file = new File(this.getServletContext().getRealPath("/")+"cookie.gif"); |
显示图片1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26// 清除输出
out.clear();
for(Cookie cookie : request.getCookies()){
if(cookie.getName().equals("file")){
// 从 Cookie 中取二进制数据
byte[] binary = BASE64Decoder.class.newInstance().decodeBuffer(URLDecoder.decode(cookie.getValue(), "UTF-8").replace(" ", ""));
// 设置内容类型为 gif 图片
response.setHeader("Content-Type", "image/gif");
response.setHeader("Content-Disposition", "inline;filename=cookie.gif");
response.setHeader("Connection", "close");
// 设置长度
response.setContentLength(binary.length);
// 输出到客户端
response.getOutputStream().write(binary);
response.getOutputStream().flush();
response.getOutputStream().close();
return;
}
}
设置Cookie的属性
name/value/maxAge/secure/path/domain/comment/version
maxAge:Cookie失效时间,单位秒。为正数表示还有多长时间失效;为负数表示临时cookie关闭浏览器即会失效;为0删除Cookie;默认为-1。
secure:Cookie是否被安全协议传输。默认为false。
path:Cookie使用路径
comment:Cookie用处说明
Session
Sesssion对应的类是javax.servlet.http.HttpSession类。第一次访问是创建key-value属性对;通过getAttribute和setAttribute来获取和设置属性;通过request.getSession()方法来获取客户Session。
- request.getSession() 若不存在,返回null;
- request.getSession(true) 若不存在,先创建Session,再返回Session。
servlet中必须使用request来获取HttpSession,而jsp中内置了Session隐藏对象,可以直接使用。
session的有效期
getMaxInactiveInterval()
setMaxInactiveInterval()
Tomcat中session默认超时时间为20分钟。
URL地址重写
session和cookie的比较
存取方式
Cookie只保存ASCII字符串,如果需要存取Unicode和二进制数据,需要进行utf-8等方式编码;Cookie不能直接存取java对象;Session可以存取任意类型数据。