会话技术概述和会话技术Cookie快速入门
会话技术概述
会话:一次会话中包含多次请求和响应。
一次会话:浏览器第一次给服务器资源发送请求,会话建立,直到有一方断开为止
功能:在一次会话的范围内的多次请求间,共享数据
方式:
客户端会话技术:Cookie
服务器端会话技术:Session
会话技术Cookie快速入门
Cookie:
1.概念:客户端会话技术,将数据保存到客户端
2.快速入门:
使用步骤:
1.创建Cookie对象,绑定数据
new Cookie(String name, String value)
2.发送Cookie对象
response.addCookie(Cookie cookie)
3.获取Cookie,拿到数据
Cookie[] request.getCookies()
创建CookieD1类
@WebServlet("/cookieD1") public class CookieD1 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //创建Cookie对象 Cookie c = new Cookie("msg", "hello"); //发送Cookie resp.addCookie(c); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } }
创建CookieD2类
@WebServlet("/cookieD2") public class CookieD2 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //获取Cookie Cookie[] cs = req.getCookies(); //获取数据,遍历Cookies if (cs!=null){ for (Cookie c : cs) { String name = c.getName(); String value = c.getValue(); System.out.println(name+""+value); } } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } }
访问1在访问2即可访问到(换个浏览器访问2是访问不到的)