在浏览器操作时,我们经常会浏览窗口并且在不同的窗体里面共享数据,例如我们上天猫,淘宝, 京东购物,我们的加入购物车以及清空购物车,都是要有数据共享的,在实现这个功能上。我们将要学习会话技术。
在JavaWeb中,会话技术分为两类,一类是Cookie,客户端会话技术,另一类是Session,服务器端的绘画技术。
(当然了,Cookie也是HttpServlet的一个子类)
关于Cookie的操作,这里给出一个Demo:
@WebServlet("/cookieDemo1")
public class CookieDemo1 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.创建Cookie对象
Cookie c = new Cookie("msg","hello");
//2.发送Cookie
response.addCookie(c);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
@WebServlet("/cookieDemo2")
public class CookieDemo2 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//3.获取Cookie
Cookie[] cs = request.getCookies();
//获取数据,遍历Cookies
if(cs != null)
{
for (Cookie c : cs) {
String name = c.getName();
String value = c.getValue();
System.out.println(name + ":" +value);
}
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
输出如上
可见键值对输出了,关于下面这个,可能是idea内部的配置相关,不了解。