Java Web学习系列(四) Servlet之Cookie与Session

创建Cookie:

1
Cookie c1 = new Cookie("foo", "bar");

发送给浏览器:

1
response.addCookie(c1);

获取Cookie:

1
2
3
4
Cookie[] cookies = request.getCookies();
for(Cookie cookie:cookies){
System.out.println(cookie.getName()+":"+cookie.getValue());
}

Session

创建Session:

1
2
HttpSession session = request.getSession(); 
session.setAttribute("username", "gtfly");

获取Session:

1
2
HttpSession session = request.getSession();
Object username = session.getAttribute("username");

立即销毁Session:

1
session.invalidate();

一个demo,输入名字后跳转输出:

首先访问login.html:

点击ok,跳转到login路由:

多次刷新,仍这样显示