会话技术
- 会话:一次会话中包含多次请求和响应。
- 一次会话:浏览器第一次给服务器资源发送请求,会话建立,知道有一方断开为止
- 功能:在一次会话的范围内的多次请求间,共享数据
- 方式:
- 客户端会话技术:Cookie
- 服务端会话技术:Session
Cookie
-
概念:客户端会话技术,将数据保存到客户端
-
快速入门:
- 使用步骤:
- 创建Cookie对象,绑定数据
- new Cookie(String name,String value)
- 发送Cookie对象
- response.addCookie(Cookie cookie)
- 获取Cookie,拿到数据
- Cookie[] request.getCookies()
- 创建Cookie对象,绑定数据
- 使用步骤:
package com.ailyt.cookie;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
/**
*
* Cookie快速入门
*
*/
@WebServlet(value = "/CookieStudy01")
public class CookieStudy01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.创建cookie对象
Cookie cookie = new Cookie("msg","hello");
//2.发送cookie
response.addCookie(cookie);
}
}
package com.ailyt.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;
/**
*
* Cookie快速入门
*
*/
@WebServlet(value = "/CookieStudy02")
public class CookieStudy02 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//3.获取cookie拿到数据
Cookie[] cs = request.getCookies();
//获取数据遍历Cookies
for (Cookie cookie1 : cs) {
System.out.println(cookie1.getName() + "--->" + cookie1.getValue());
}
}
}
会话技术Cookie原理分析
- 基于响应头set-cookie和请求头cookie实现