浏览器第一次给服务器发起请求,就建立一次会话,直到一方断开连接为止。
在一次会话范围内的多次请求之间共享数据
使用的步骤:
cookie原理:
这是基于响应头Set-Cookie和请求头Cookie实现的。
Set-Cookie: message=helloWorld
,发送给浏览器,浏览器获得该响应消息,保存该信息Cookie: message=helloWorld;
,发送给服务器。Cookie的一些细节
setMaxAge(int second)
设置存活时间,进行持久化处理
setPath(String path)
来设置,默认情况下就是当前项目。如果需要多个项目共享该Cookie对象,就可以设置为 setPath("/")
表示当前项目的根路径下的所有项目共享xxx.alibaba.com
之间的项目都可共享cookieCookie的特点
Cookie的作用
使用cookie实现展示上一次访问时间的小功能:
@WebServlet("/AccessTimeServlet")
public class AccessTimeServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
Cookie[] cookies = request.getCookies();
boolean flag = false;
if (cookies != null && cookies.length != 0) {
for (Cookie cookie : cookies) {
if ("lastTime".equals(cookie.getName())) {
flag = true;
String lastTime = URLDecoder.decode(cookie.getValue(), "utf-8");
response.getOutputStream().write(("欢迎再次访问,您上次访问时间为:" + lastTime).getBytes("utf-8"));
Date date = new Date();
String str_date = "yyyy年MM月dd日 hh:mm:ss";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(str_date);
str_date = simpleDateFormat.format(date);
str_date = URLEncoder.encode(str_date, "utf-8");
cookie.setValue(str_date);
response.addCookie(cookie);
}
}
}
if (cookies == null || cookies.length == 0 || !flag) {
response.getOutputStream().write("欢迎您第一次访问".getBytes("utf-8"));
Date date = new Date();
String str_date = "yyyy年MM月dd日 hh:mm:ss";
SimpleDateFormat format = new SimpleDateFormat(str_date);
str_date = format.format(date);
str_date = URLEncoder.encode(str_date, "utf-8");
Cookie cookie = new Cookie("lastTime", str_date);
response.addCookie(cookie);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
原文:https://www.cnblogs.com/zhuobo/p/10787697.html