Cookie:主要用来保存客户端的一些数据,保存在浏览器中,在Header访问服务器让服务器识别,不安全,而且储存的大小只有4KB
代码实现
//保存用户上一次访问的时间做为Cookie
public class CookieDemo01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//服务器,告诉你,把你(浏览器访问网页)来的这个时间封装成一个信件Cookie,你下次带来,我就知道你来了
//解决请求和响应的中文乱码
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
PrintWriter out = resp.getWriter();
//Cookie,服务端从客户端获取cookie
Cookie[] cookies = req.getCookies(); //这里返回数组,说明Cookie可能存在多个
//判断从客户端获取的Cookie是否存在
if (cookies != null){
//如果存在Cookie
out.write("你上一次访问的时间是:");
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
//获取cookie的名字
if (cookie.getName().equals("lastLoginTime")){
//获取cookie中的值,并且输出,因为为string类型,我们要输出为时间类型,所以需要转换为long类型
long lastLoginTime = Long.parseLong(cookie.getValue());
Date date = new Date(lastLoginTime); //转换为时间类型
out.write(date.toLocaleString());
out.write(cookie.getValue());
}
}
}else{
out.write("这是你第一次访问网站,你没有Cookie保存"); //浏览器网页输出
}
//最后服务给客户端(浏览器)更新响应一个新的Cookie
resp.addCookie(new Cookie("lastLoginTime",System.currentTimeMillis()+""));
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
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"
metadata-complete="true">
<!-- Servlet注册,Cookie的获取,给与-->
<servlet>
<servlet-name>CookieDemo01</servlet-name>
<servlet-class>com.hwh.servlet.CookieDemo01</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CookieDemo01</servlet-name>
<url-pattern>/c1</url-pattern>
</servlet-mapping>
</web-app>
实现的效果,浏览器的网页请求Headers