CookieDemoServlet.java
package blank.servlet;
import java.io.IOException;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CookieDemoServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//定义cookie对象
Cookie cookie = null;
//请求request中
Cookie cookies[] = request.getCookies();
//遍历cookies信息
if(cookies!=null){
for(Cookie ck:cookies){
//获取每个cookie中的信息
System.out.println(ck.getName()); //cookie的名称
System.out.println(ck.getValue()); //对应的value值
System.out.println(ck.getPath()); //有效目录
System.out.println(ck.getMaxAge());//在浏览器上 cookie有效时间
System.out.println(ck.getDomain());//有效的域
String name = ck.getName();
//判断cookie是否存在
if("lasttimes".equals(name)){
cookie=ck;
}
}
}
//添加一个cookie
if(cookie==null){
//创建一个cookie对象 name value值
cookie=new Cookie("lasttimes", System.currentTimeMillis()+"");
System.out.println("====create==cookie=====");
}
request.setAttribute("lasttimes", new Date(Long.valueOf(cookie.getValue())));
//重新改变值
cookie.setValue(System.currentTimeMillis()+"");
//添加到响应中
response.addCookie(cookie);
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!-- <link rel="stylesheet" type="text/css" href="styles.css"> -->
</head>
<body>
<div>上次访问的时间:${lasttimes}</div>
<div>
<a href="./ck.do">第一次访问</a>
</div>
</body>
</html>
版权声明:本文为博主原创文章,未经博主允许不得转载。