会话技术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.cookie; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.annotation.*; import java.io.IOException; /** * cookie快速入门 */ @WebServlet("/cookieDemo1") public class cookieDemo1 extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1.创建Cookie对象 Cookie c = new Cookie("msg", "hello"); // 2.发送Cookie response.addCookie(c); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
package com.example.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 { @Override 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); } } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
会话技术Cookie原理分析
一、会话技术分类
1、Cookie技术
(1)Cookie是客户端技术,程序把每个用户的数据以cookie的形式保存到各自的浏览器中,
(2)当用户使用浏览器再次访问服务器中的Web资源的时候,就会带着各自的数据过去。
标签:入门,request,response,会话,Cookie,import,servlet,javax From: https://www.cnblogs.com/wsfj/p/17107945.html