1.在servlet中
HttpSession session = request.getSession();
session.setAttribute()
session.getAttribute()
其余的都和jsp一样
2.在jsp中
设置session 属性名 值
session.setAttribute("user","李四");
设置当前会话对象有效期,默认是30分钟,现在设置1000秒。
session.setMaxInactiveInterval(1000);
销毁当前会话域中的所有属性
request.getSession().invalidate();
request.getSession().removeAttribute("username"); //假设当前session域对象中已经有属性名为username的属性
当你不想买某件商品时,直接session.removeAttribute("goodx");(x为1,2,3,4代表商品),从购物车中移除。
如果使用invalidate(),清除了购物车中所有商品。
3.cookie
建立设置cookie
Cookie u = new Cookie("name","李四");
u.setMaxAge(1000);
response.addCookie(u);
删除
Cookie u = new Cookie("age", "");
u.setMaxAge(-1);
response.addCookie(u);
读取cookie
Cookie[] cs = request.getCookies();
out.print(cs.length);
for (Cookie c : cs) {
if (c.getName().equals("name")) {
out.print(c.getValue());
break;
}
}
判断一个cookie有没有
String cname = "name";
boolean result = false;
for(Cookie c :cs){
if(c.getName().equals(cname)){
result = true;
break;
}
}
out.print("<hr>");
if(result){
out.print("有cookie - "+cname);
out.print(cu.getCookie(cname));
}else{
out.print("没有cookie "+cname);
}