会话技术-Cookie-快速入门
1. 概念:客户端会话技术,将数据保存到客户端
2. 快速入门:
使用步骤:
1. 创建Cookie对象,绑定数据
new Cookie(String name, String value)
2. 发送Cookie对象
response.addCookie(Cookie cookie)
3. 获取Cookie,拿到数据
Cookie[] request.getCookies()
package com.example.day_16_cookidsession.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("/cookieDemo1") public class CookieDemo1 extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1.创建Cookie对象 Cookie c = new Cookie("msg","hello"); //2.发送Cookie response.addCookie(c); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
package com.example.day_16_cookidsession.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("/cookieDemo2") public class CookieDemo2 extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //3. 获取Cookie Cookie[] cs = request.getCookies(); //获取数据,遍历Cookies if(cs != null){ for (Cookie c : cs) { String name = c.getName(); String value = c.getValue(); System.out.println(name+":"+value); } } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
会话技术-Cookie-原理分析
一、会话技术分类
1、Cookie技术
(1)Cookie是客户端技术,程序把每个用户的数据以cookie的形式保存到各自的浏览器中,
(2)当用户使用浏览器再次访问服务器中的Web资源的时候,就会带着各自的数据过去。
标签:http,入门,response,会话,Cookie,import,servlet,javax From: https://www.cnblogs.com/yuzong/p/16942340.html