Cookie的使用
Posted 咖啡加糖
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Cookie的使用相关的知识,希望对你有一定的参考价值。
一.什么是 Cookie?
1、Cookie 翻译过来是饼干的意思。
2、Cookie 是服务器通知客户端保存键值对的一种技术。
3、客户端有了 Cookie 后,每次请求都发送给服务器。
4、每个 Cookie 的大小不能超过 4kb
二.项目案例
1.目录结构
2.CookieServlet类
package com.atguigu.servlet; import com.atguigu.util.CookieUtils; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class CookieServlet extends BaseServlet { /** * 创建Cookie * @param req * @param resp * @throws ServletException * @throws IOException */ protected void createCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1 创建Cookie对象 Cookie cookie = new Cookie("key4", "value4"); //2 通知客户端保存Cookie resp.addCookie(cookie); //1 创建Cookie对象 Cookie cookie1 = new Cookie("key5", "value5"); //2 通知客户端保存Cookie resp.addCookie(cookie1); resp.getWriter().write("Cookie创建成功"); } /** * 获取Cookie * @param req * @param resp * @throws ServletException * @throws IOException */ protected void getCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Cookie[] cookies = req.getCookies(); for (Cookie cookie : cookies) { // getName方法返回Cookie的key(名) // getValue方法返回Cookie的value值 resp.getWriter().write("Cookie[" + cookie.getName() + "=" + cookie.getValue() + "] <br/>"); } //根据名称获取cookie Cookie iWantCookie = CookieUtils.findCookie("key1", cookies); // 如果不等于null,说明赋过值,也就是找到了需要的Cookie if (iWantCookie != null) { resp.getWriter().write("找到了需要的Cookie"); } } /** * 修改Cookie * @param req * @param resp * @throws ServletException * @throws IOException */ protected void updateCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //方案一: //1、先创建一个要修改的同名的Cookie对象 //2、在构造器,同时赋于新的Cookie值。 //Cookie cookie = new Cookie("key1","newValue1"); //3、调用response.addCookie( Cookie ); 通知 客户端 保存修改 //resp.addCookie(cookie); //方案二: //1、先查找到需要修改的Cookie对象 Cookie cookie = CookieUtils.findCookie("key4", req.getCookies()); if (cookie != null) { //2、调用setValue()方法赋于新的Cookie值。 cookie.setValue("newValue4"); //3、调用response.addCookie()通知客户端保存修改 resp.addCookie(cookie); } resp.getWriter().write("key4的Cookie已经修改好"); } /** * 默认的会话级别的Cookie * @param req * @param resp * @throws ServletException * @throws IOException */ protected void defaultLife(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Cookie cookie = new Cookie("defalutLife","defaultLife"); cookie.setMaxAge(-1);//设置存活时间 resp.addCookie(cookie); } /** * 马上删除一个Cookie * @param req * @param resp * @throws ServletException * @throws IOException */ protected void deleteNow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 先找到你要删除的Cookie对象 Cookie cookie = CookieUtils.findCookie("key4", req.getCookies()); if (cookie != null) { // 调用setMaxAge(0); cookie.setMaxAge(0); // 表示马上删除,都不需要等待浏览器关闭 // 调用response.addCookie(cookie); resp.addCookie(cookie); resp.getWriter().write("key4的Cookie已经被删除"); } } /** * 设置存活1个小时的Cooie * @param req * @param resp * @throws ServletException * @throws IOException */ protected void life3600(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Cookie cookie = new Cookie("life3600", "life3600"); cookie.setMaxAge(60 * 60); // 设置Cookie一小时之后被删除。无效 resp.addCookie(cookie); resp.getWriter().write("已经创建了一个存活一小时的Cookie"); } protected void testPath(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Cookie cookie = new Cookie("path1", "path1"); // getContextPath() ===>>>> 得到工程路径 cookie.setPath( req.getContextPath() + "/abc" ); // ===>>>> /工程路径/abc resp.addCookie(cookie); resp.getWriter().write("创建了一个带有Path路径的Cookie"); } }
3.BaseServlet类
package com.atguigu.servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.lang.reflect.Method; public abstract class BaseServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 解决post请求中文乱码问题 // 一定要在获取请求参数之前调用才有效 req.setCharacterEncoding("UTF-8"); // 解决响应中文乱码问题 resp.setContentType("text/html; charset=UTF-8"); String action = req.getParameter("action"); try { // 获取action业务鉴别字符串,获取相应的业务 方法反射对象 Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class); // System.out.println(method); // 调用目标业务 方法 method.invoke(this, req, resp); } catch (Exception e) { e.printStackTrace(); } } }
4.LoginServlet类
package com.atguigu.servlet; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class LoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String username = req.getParameter("username"); String password = req.getParameter("password"); if ("wzg168".equals(username) && "123456".equals(password)) { //登录 成功 Cookie cookie = new Cookie("username", username); cookie.setMaxAge(60 * 60 * 24 * 7);//当前Cookie一周内有效 resp.addCookie(cookie); System.out.println("登录 成功"); } else { // 登录 失败 System.out.println("登录 失败"); } } }
5.CookieUtils类
package com.atguigu.util; import javax.servlet.http.Cookie; public class CookieUtils { /** * 查找指定名称的Cookie对象 * @param name * @param cookies * @return */ public static Cookie findCookie(String name , Cookie[] cookies){ if (name == null || cookies == null || cookies.length == 0) { return null; } for (Cookie cookie : cookies) { if (name.equals(cookie.getName())) { return cookie; } } return null; } }
6.web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <servlet> <servlet-name>CookieServlet</servlet-name> <servlet-class>com.atguigu.servlet.CookieServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>CookieServlet</servlet-name> <url-pattern>/cookieServlet</url-pattern> </servlet-mapping> <servlet> <servlet-name>LoginServlet</servlet-name> <servlet-class>com.atguigu.servlet.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/loginServlet</url-pattern> </servlet-mapping> </web-app>
7.cookie.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="pragma" content="no-cache" /> <meta http-equiv="cache-control" content="no-cache" /> <meta http-equiv="Expires" content="0" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Cookie</title> <base href="http://localhost:8080/cookie_session/"> <style type="text/css"> ul li { list-style: none; } </style> </head> <body> <iframe name="target" width="500" height="500" style="float: left;"></iframe> <div style="float: left;"> <ul> <li><a href="cookieServlet?action=createCookie" target="target">Cookie的创建</a></li> <li><a href="cookieServlet?action=getCookie" target="target">Cookie的获取</a></li> <li><a href="cookieServlet?action=updateCookie" target="target">Cookie值的修改</a></li> <li>Cookie的存活周期</li> <li> <ul> <li><a href="cookieServlet?action=defaultLife" target="target">Cookie的默认存活时间(会话)</a></li> <li><a href="cookieServlet?action=deleteNow" target="target">Cookie立即删除</a></li> <li><a href="cookieServlet?action=life3600" target="target">Cookie存活3600秒(1小时)</a></li> </ul> </li> <li><a href="cookieServlet?action=testPath" target="target">Cookie的路径设置</a></li> <li><a href="" target="target">Cookie的用户免登录练习</a></li> </ul> </div> </body> </html>
8.login.jsp
<%-- Created by IntelliJ IDEA. User: Administrator Date: 2020/2/10 Time: 11:34 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <form action="http://localhost:8080/cookie_session/loginServlet" method="get"> 用户名:<input type="text" name="username" value="${cookie.username.value}"> <br> 密码:<input type="password" name="password"> <br> <input type="submit" value="登录"> </form> </body> </html>
二.如何创建 Cookie
Servlet 程序中的代码:
protected void createCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1 创建Cookie对象 Cookie cookie = new Cookie("key4", "value4"); //2 通知客户端保存Cookie resp.addCookie(cookie); //1 创建Cookie对象 Cookie cookie1 = new Cookie("key5", "value5"); //2 通知客户端保存Cookie resp.addCookie(cookie1); resp.getWriter().write("Cookie创建成功"); }
三.服务器如何获取 Cookie
服务器获取客户端的 Cookie 只需要一行代码:req.getCookies():Cookie[]
protected void getCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Cookie[] cookies = req.getCookies(); for (Cookie cookie : cookies) { // getName方法返回Cookie的key(名) // getValue方法返回Cookie的value值 resp.getWriter().write("Cookie[" + cookie.getName() + "=" + cookie.getValue() + "] <br/>"); } //根据名称获取cookie Cookie iWantCookie = CookieUtils.findCookie("key1", cookies); // 如果不等于null,说明赋过值,也就是找到了需要的Cookie if (iWantCookie != null) { resp.getWriter().write("找到了需要的Cookie"); } }
四.Cookie 值的修改
方案一:
1、先创建一个要修改的同名(指的就是 key)的 Cookie 对象
2、在构造器,同时赋于新的 Cookie 值。
3、调用 response.addCookie( Cookie );
方案二:
1、先查找到需要修改的 Cookie 对象
2、调用 setValue()方法赋于新的 Cookie 值。
3、调用 response.addCookie()通知客户端保存修改
五.Cookie 生命控制
Cookie 的生命控制指的是如何管理 Cookie 什么时候被销毁(删除)
setMaxAge()
正数,表示在指定的秒数后过期
负数,表示浏览器一关,Cookie 就会被删除(默认值是-1)
零,表示马上删除 Cookie
六.Cookie 有效路径 Path 的设置
Cookie 的 path 属性可以有效的过滤哪些 Cookie 可以发送给服务器。哪些不发。
path 属性是通过请求的地址来进行有效的过滤。
CookieA path=/工程路径
CookieB path=/工程路径/abc
请求地址如下:
http://ip:port/工程路径/a.html
CookieA 发送
CookieB 不发送
http://ip:port/工程路径/abc/a.html
CookieA 发送
CookieB 发送
以上是关于Cookie的使用的主要内容,如果未能解决你的问题,请参考以下文章
Django cookie 横幅:window.wpcc 未定义