会话技术
##1. 会话:一次会话中包含多次请求和响应
* 一次会话:浏览器第一次和服务器资源发送请求,会话建立,直到有一方断开为止
即:

什么是会话呢? 所谓的会话过程就是指从打开浏览器到关闭浏览器的过程。

2. 功能:在一次会话的范围内 共享数据

3. 方式:

  1. 1. 客户端会话技术:Cookie
  2. 2. 服务器端会话技术:Session(Java)

Cookie
##1.概念: 客户端会话技术,用于客户端保存数据
##2.快速入门
使用步骤
1. 创建Cookie对象,绑定数据;
new Cookie(String name, String value);
2. 发送Cookie对象;
response.addCookies(Cookie cookie);
3. (Servlet)获取Cookie。
* Cookie[] cookies = request.getCookies();
##示例代码

Demo1:创建Cookie 并从响应中发送给浏览器

  1. @WebServlet("/cookieDemo1")
  2. public class CookieDemo1 extends HttpServlet {
  3. @Override
  4. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  5. //创建Cookies
  6. Cookie cookie = new Cookie("msg","Hello");
  7. //发送Cookie
  8. response.addCookie(cookie);
  9. }
  10. @Override
  11. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  12. this.doPost(request, response);
  13. }
  14. }

Demo2:服务器获取Cookie

  1. @WebServlet("/cookieDemo2")
  2. public class CookieDemo2 extends HttpServlet {
  3. @Override
  4. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  5. Cookie[] cookies = request.getCookies();
  6. if (cookies != null){
  7. for (Cookie cookie : cookies) {
  8. System.out.println(String.format("cookie's name : %s,value : %s . %s",cookie.getName(),cookie.getValue(),"\n"));
  9. }
  10. }
  11. }
  12. @Override
  13. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  14. this.doPost(request, response);
  15. }
  16. }

3. Cookie实现原理: