会话
作用:每个用户与服务器在会话的过程中产生一些数据,我们作为程序希望保存用户在会话过程中产生的数据,保存在会话对象中
概念
Cookie是客户端技术, 默认保存在客户端的浏览器缓存中应用程序将用户的数据以cookie的方式存在浏览器上,当客户端访问服务器的时候,都会携带自己的cookie数据
Cookie是服务器创建的,保存在客户端(http协议)Cookie可以完成服务器与客户端的数据传输
path
我在/page/index/index.html中向浏览器添加了一个useid的cookie(这里没有指定path), 然后试着从/page/demo/demo.html中取值,发现无法取到,
通过开发者工具查看发现userid的path是/page/index/, 所以无法在page/demo/下面取到, 解决办法就是在添加cookie时指定path为/page/, 这时page目录下的所有页面都可以获取到userid
另外, path只能设置为绝对路径
常用方法
Cookie是一个对象,与request和response打交道时用。 单独与Cookie打交道用Cookie的成员方法。
•
public Cookie[] request.getCookies()
返回包含客户端随此请求一起发送的所有 Cookie 对象的数组
•
${cookie.lasttime.value}
•
public void response.addCookie(Cookie cookie)
将指定 cookie 添加到响应
创建Cookie
•
public Cookie(String name, String value)
构造带指定名称和值的 cookie。
•
void setValue(String newValue)
•
setPath('/') 设置生效范围
•
String getName()
•
String getValue()
•
public void setMaxAge(int expiry)
设置 cookie 的最大生存时间,以秒为单位。设置为0就是删除,设置为负数
//获取客户端发送的所有cookie
Cookie [] cks = req.getCookies();
Cookie c = null;
//遍历cookie数组,找保存上一次访问时间的cookie
if(cks != null){
for (Cookie cookie : cks) {
if(cookie.getName().equals("lasttime")){
c = cookie;
}
}
}
//如果c为null,说明是第一次访问
if(c == null){
resp.getWriter().write("欢迎你,第一个访问");
//创建cookie,放入当前系统时间
c = new Cookie("lasttime",new Date().toLocaleString());
//c.setMaxAge(365*24*60*60);
}else{
//获取该cookie的值
String time = c.getValue();
resp.getWriter().write("你上一次访问的时间是"+time);
//将系统时间写入cookie
c.setValue(new Date().toLocaleString());
//c.setMaxAge(365*24*60*60);
}
c.setPath("/");//设置cookie在整个应用有效
//写回cookie
resp.addCookie(c);
//获取请求中的cookie
Cookie [] cks = req.getCookies();
String pid = req.getParameter("pid");
Cookie c = null;
if(cks != null){
for (Cookie cookie : cks) {
if(cookie.getName().equals("products")){
c = cookie;
}
}
}
// 1,2
if(c == null){
//第一次产生浏览记录
c = new Cookie("products",pid);
}else{
//获取cookie中的商品
String str = c.getValue();
String [] p = str.split(",");
boolean find = false;
for (String string : p) {
if(string.equals(pid)){
find = true;
}
}
//1,2,3
if(find == false){
str = str + ","+pid;
c.setValue(str);
}
}
resp.addCookie(c);
//重定向到商品列表页面
resp.sendRedirect("/day03/product_list.jsp");
${cookie.lasttime.value}
<img src="${pageContext.request.contextPath }/cmf.jpg"/>
<a href="${pageContext.request.contextPath }/addHistory?pid=1">新疆炒米粉</a>
<c:choose>
<c:when test="${empty cookie.products }">
<h3>没有浏览记录</h3>
</c:when>
<c:otherwise>
${cookie.products.value}
</c:otherwise>
</c:choose>
评论区