版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
BUG问题
1.该问题是无法利用new Date对cookies设置值.能打印,转为字符串也行,代码真没问题但是就是不行.
解决方法:利用system.cruentTimeMillis获取秒数,然后利用new Date()的构造函数解决.
但是我总感觉不是代码出现了问题,而是…自己试试我也想知道
修改之前:
/*
* 使用Cookie记录客户端上次访问的时间
*
* 思路:
* 访问时获取想要的Cookie 如果没有获取到说明是第一次访问,把当前时间存到一个Cookie中响应给客户端
* 如果获取到了,从cookie中取时间(上次访问时间),再把当前时间存入Cookie中
*
* */
public class CookieDemo4Servlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
Cookie[] cs = request.getCookies();
Cookie c = CookieUtils.findCookieByName("lasttime", cs);
/*if(cs!=null){
for(Cookie cc:cs){
if(cc.getName().equals("lasttime")){
c = cc;
break;
}
}
}*/
if(c!=null){
out.print("<h1>上次访问时间为:"+c.getValue()+"</h1>");
}else{ //第一次访问
out.print("<h1>欢迎第一次访问</h1>");
}
Cookie cookie = new Cookie("lasttime",new Date()+"");
cookie.setMaxAge(10000);
response.addCookie(cookie);
}
}
修改之后:
/*
* 使用Cookie记录客户端上次访问的时间
*
* 思路:
* 访问时获取想要的Cookie 如果没有获取到说明是第一次访问,把当前时间存到一个Cookie中响应给客户端
* 如果获取到了,从cookie中取时间(上次访问时间),再把当前时间存入Cookie中
*
* */
@WebServlet("/CookieDemo4Servlet")
public class CookieDemo4Servlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
Cookie[] cs = request.getCookies();
Cookie c = CookieUtils.findCookieByName("lasttime", cs);
/*if(cs!=null){
for(Cookie cc:cs){
if(cc.getName().equals("lasttime")){
c = cc;
break;
}
}
}*/
if(c!=null){
long cookieValue = Long.parseLong (c.getValue ( )); //得到用户的上次访问时间
Date date = new Date (cookieValue); //将long转换为日期
out.print("<h1>上次访问时间为:"+date+"</h1>");
}else{ //第一次访问
out.print("<h1>欢迎第一次访问</h1>");
}
Cookie cookie = new Cookie("lasttime",System.currentTimeMillis () + "");
cookie.setMaxAge(60*20*24);
cookie.setPath ("/");
response.addCookie(cookie);
}
}
涉及到的cookie工具类
public class CookieUtils {
public static Cookie findCookieByName(String name,Cookie[] cs){
if(cs!=null){
for(Cookie c:cs){
if(name.equals(c.getName())){
return c;
}
}
}
return null;
}
}