会话技术_概述与会话技术_Cookie_快速入门

会话技术_概述

    会话技术

        1.Cookie

        2.Session

  会话技术,按照道理来说就像人与人之间的对话一样,你一句我一答,只不过其中的角色换成了服务器端和客户端  

 

 

 

 

           1.会话: 一次会话中包含多次请求和响应

            一次会话:浏览器第一次给服务器资源发送请求,会话建立,直到有一方断开为止

           2.功能:在一次会话的范围内的多次请求间,共享数据

           3.方式:

             1.客户端会话技术:Cookie

             2.服务器端会话技术:Session  

        

 

会话技术_Cookie_快速入门

      Cookie:    

        1.概念:客户端会话技术,将数据保存到客户端

        2.快速入门:

          使用步骤:

              1.创建Cookie,绑定数据

                 new Cookie(String name, String value)

              2.发送对象

                 response.addCookie(Cookie cookie) 

              3.获取Cookie,拿到数据    

               Cookie[]  resquest.  getCookies()

package bd.xueqiang.Cookie;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet("/cookieDemo01")
public class CookieDemo01 extends HttpServlet {
    /**
     * Cookis快速入门
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                //1.创建Cookie对象
        Cookie msg = new Cookie("msg", "hello");
                //2.发送Cookis
        response.addCookie(msg);



    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
package bd.xueqiang.Cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/cookieDemo02")
public class CookieDemo02 extends HttpServlet {
    /**
     * Cookis快速入门
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //3.获取Cookis
        Cookie[] cookies = request.getCookies();
        //获取数据,遍历Cookis
        if (cookies!=null){
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                String value = cookie.getValue();
                System.out.println(name+":"+value);
            }
        }


    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

 

 

 

 

 

 


 
posted @ 2023-02-08 16:52  zj勇敢飞,xx永相随  阅读(30)  评论(0编辑  收藏  举报