package priv.dandelion.controller;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("/cookieDemoA")public class AServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 创建Cookie对象 Cookie cookie = new Cookie("name","zhangsan"); // 通过resp将Cookie发送到前端 resp.addCookie(cookie); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); }}
- 获取客户端携带的所有Cookie数组,使用Request对象
Cookie[] cookies = request.getCookies(); - 使用Cookie对象的方法获取数据
cookie.getName();cookie.getValue(); - 案例
需求:在Servlet中获取前一个案例存入在Cookie对象中的数据
1.编写一个新Servlet类,名称为BServlet
2.在BServlet中使用request对象获取Cookie数组,遍历数组,从数据中获取指定名称对应的值
3.启动测试,在控制台打印出获取的值
- 编写Servlet,使用request对象获取Cookie数组,遍历数组,从数据中获取指定名称对应的值,并在控制台打印
package priv.dandelion.controller;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("/cookieDemoB")public class BServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cookie[] cookies = request.getCookies(); for (Cookie cookie : cookies) { if ("username".equals(cookie.getName())) { System.out.println(cookie.getName() + "," + cookie.getValue()); break; } } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); }} - 大数据技术之HBase原理与实战归纳分享-中
- 电子信息工程专业和电子信息科学与技术专业有什么区别 哪个更好就业
- 生物技术专业和生物科学专业有什么区别 哪个更好就业
- 详解ROMA Connect API 流控实现技术
- 小鸡养殖技术与管理
- nmr是什么
- 控制测量技术设计书
- 大数据技术之HBase原理与实战归纳分享-上
- 四川师范大学应用技术学院怎么样
- Java核心技术阅读笔记 java中的自动拆装箱与缓存