Cookie
路径如下图
注意这是一个Maven项目,依赖如下:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
<scope>provided</scope>
</dependency>
另外我将这个项目的访问地址如下设置:
正式开始
先写一个cookie,功能是在第二次访问的时候返回一个上一次访问的时间。代码如下,功能看注释:
package com.huangdekai.JavaWeb;
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;
import java.io.PrintWriter;
import java.util.Date;
/**
* @Autord: HuangDekai
* @Date: 2020/4/18 18:05
* @Version: 1.0
* @since: jdk11
*/
//保存用户上一次访问的时间
public class a01_CookieDemo extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 服务器,告诉你,你来的时间,把这个时间封装成为一个 信件,你下次带来,我就知道你来了
// 解决chrome中文乱码
req.setCharacterEncoding("utf-16");
resp.setCharacterEncoding("utf-16");
PrintWriter out = resp.getWriter();
// Cookie,服务器端从客户端获取:
Cookie[] cookies = req.getCookies();//这里返回数组,说明Cookie可能存在多个
// 判断Cookie是否存在
if (cookies != null) {
// 如果存在怎么办
out.write("你上一次访问的时间是:");
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
//获取cookie的名字
if (cookie.getName().equals("lastLoginTime")) {
//获取cookie中的值
long lastLoginTim = Long.parseLong(cookie.getValue());
Date date = new Date(lastLoginTim);
out.write(String.valueOf(date));
}
}
}else {
out.write("这是您第一次访问本站");
}
// 服务器给客户端响应一个Cookie
Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis()+"");
// cookie有效期为一天
cookie.setMaxAge(24*60*60);
//将cookie响应到客户端
resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
记得修改web.xml,写好servlet
<?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"
metadata-complete="true">
<servlet>
<servlet-name>a01_CookieDemo</servlet-name>
<servlet-class>com.huangdekai.JavaWeb.a01_CookieDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>a01_CookieDemo</servlet-name>
<url-pattern>/cookie1</url-pattern>
</servlet-mapping>
</web-app>
部署到Tomcat上,访问在Tomcat、Servlet设定好的地址:
再次访问
当前时间是:
那么在这里可以思考一个问题,cookie的有效期,即
cookie.setMaxAge()
可以设置为0吗?
答案是可以。并且可以实现如下效果:
package com.huangdekai.JavaWeb;
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;
/**
* @Autord: huangdekai
* @Date: 2020/4/20 12:58
* @Version: 1.0
* @since: jdk11
*/
public class a02_CleanCookieDemo extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie[] cookies = req.getCookies();
Cookie cookie = new Cookie("lastLoginTime","clean");
cookie.setMaxAge(0);
resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
记得将servlet补上:
<servlet>
<servlet-name>a02_CleanCookieDemo</servlet-name>
<servlet-class>com.huangdekai.JavaWeb.a02_CleanCookieDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>a02_CleanCookieDemo</servlet-name>
<url-pattern>/clean</url-pattern>
</servlet-mapping>
重新部署Tomcat之后,访问cookie1:
可以发现我们上一次访问时候服务端给客户端发的cookie
现在访问clrean:
因为没有在前台写任何东西,自然是空白的
这时候再回去访问cookie1:
cookie已经没有了
也就是说,可以用一个同名的cookie去替换一个cookie,并用setMaxAge将其最大生命设置为0,去删除这个cookie。
另外,如果cookie的值是中文(如下1图,cookie由key=value组成),为了避免各种各种莫名其妙的编码问题,建议使用URLEncoder和URLDecoder进行编码
package com.huangdekai.JavaWeb;
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;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
/**
* @Autord: 黄德铠
* @Date: 2020/4/20 13:04
* @Version: 1.0
* @since: jdk11
*/
public class a03_CookieDemo extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 设置编码,解决中文乱码问题
req.setCharacterEncoding("utf-16");
resp.setCharacterEncoding("utf-16");
// 此处命名为out有关后面Session内容
PrintWriter out = resp.getWriter();
// 服务端从客户端获取Cookie
Cookie[] cookies = req.getCookies();
// 要传输的文字,如果是中文,最好先进行编码解码URLEncoder、URLDecoder
if (cookies != null) {
out.write("您是:");
for (Cookie cookie : cookies) {
if (cookie.getName().equals("name")){
out.write(URLDecoder.decode(cookie.getValue(),"utf-16"));
}
}
} else {
out.write("这是您第一次访问本站");
}
String value = "杜撰";
String encode = URLEncoder.encode(value, "utf-16");
Cookie name = new Cookie("name", encode);
resp.addCookie(name);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
同样,第一次是没有显示cookie的,第二次访问就会显示出来: