Cookie和Session是两种会话技术。
Cookie是客户端技术。
Session是服务端技术。
1:存入Cookie
1 2 3 4 5 6 7 8
| String value = "中文"; value = URLEncoder.encode(value,"utf-8");
Cookie c = new Cookie("key",value);
c.setMaxAge(30*60);
response.addCookie(c);
|
2:取出Cookie
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| Cookie[] cookies = request.getCookies();
if(cookies==null || cookies.length==0){ response.getWriter().println("获取cookie失败!"); }else{ for(Cookie c:cookies){ if(c.getName().equals("key")){ String value = c.getValue(); value= URLDecoder.decode(value,"utf-8"); response.getWriter().println("上次访问用户名是:"+value); } } }
|
3:创建Session
1 2 3 4
| HttpSession session = request.getSession();
response.getWriter().print("给您生成的sessionid是:"+session.getId());
|