会话技术_概述
概念:一次会话中包含多次请求和响应
-
- 一次会话:浏览器第一次给服务器资源发送请求 会话建立 直到一方断开为止
功能:在一次会话的范围内的多次请求间 共享数据
方式:
- 客户端会话技术:Cookie
- 服务器端会话技术:Session
会话技术_快速入门
会话技术:Cookie
Cookie概念:客户端会话技术 将数据保存到客户端
快速入门:
- 使用步骤
- 创建Cookie对象 绑定数据
- new Cookie(String name,String value)
- 发送Cookie对象
- responese.addCookie(Cookie cookie)
- 获取Cookie 拿到数据
- Cookie[] request.getCookies()
- 创建Cookie对象 绑定数据
java代码
CookieDemo01类
package com.bai.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("/CookieDemo01") public class CookieDemo01 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //创建Cookie对象 Cookie cookie = new Cookie("msg", "hello"); //发送Cookie resp.addCookie(cookie); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
CookieDemo02类
package com.bai.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 { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //创建Cookie对象 Cookie[] cookies = req.getCookies(); if (cookies!=null){ for (Cookie cookie : cookies) { String name = cookie.getName(); String value = cookie.getValue(); System.out.println(name+":"+value); } } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
运行结果
Cookie_原理分析
图解
标签:http,入门,会话,概述,Cookie,import,servlet,javax From: https://www.cnblogs.com/aimz01/p/16587245.html