2 baidu 24882769 baidu_24882769 于 2015.07.11 10:59 提问

关于jsp中利用cookie记录上次登录时间和IP的问题

<%

String IP = request.getRemoteAddr();
Cookie[] cookies = request.getCookies();
Cookie serverCookie=null;
for(int i=0;i<cookies.length;i++)
    if(IP.equals(cookies[i].getName())){
        serverCookie=cookies[i];}
if(serverCookie==null){
    Date date = new Date();
    String time = date.getYear()+"年"+date.getMonth()+"月"+date.getDay()+"日"+date.getHours()+"时"+date.getMinutes()+"分";
    serverCookie = new Cookie(IP,time); 
    serverCookie.setMaxAge(300);
    response.addCookie(serverCookie);
    out.println("尊敬的用户,欢迎您首次访问本网站!");
    out.println("<BR>您本次访问本网站的时间是:"+time);
    out.println("<BR>使用的IP地址是:"+IP);}
else{
    String IPS = serverCookie.getName();
    String times = serverCookie.getValue();
    out.println("尊敬的用户,欢迎您访问本网站!");
    out.println("<BR>您上次访问本网站的时间是:"+times);
    out.println("<BR>使用的IP地址是:"+IPS);
    }

%>

这里是程序代码,运行时网页上提示for循环的那行有问题,求大神解答

4个回答

Evankaka
Evankaka   Ds   Rxr 2015.07.11 11:51
Evankaka
Evankaka   Ds   Rxr 2015.07.11 11:54
Evankaka
Evankaka   Ds   Rxr 2015.07.11 11:55

package com.mucfc;

import java.io.IOException;
import java.io.PrintWriter;
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;

/**

  • cookied测试
  • @author 林炳文Evankaka(博客:http://blog.csdn.net/evankaka)
  • @since 2015.6.24
    */
    public class CookiedServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

    //设置浏览器以UTF-8编码进行接收,解决中文乱码问题
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    //获取浏览器访问访问服务器时传递过来的cookie数组
    Cookie[] cookies = request.getCookies();
    //如果用户是第一次访问,那么得到的cookies将是null
    if (cookies!=null) {
        out.write("您上次访问的时间是:");
        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            if (cookie.getName().equals("lastAccessTime")) {
                Long lastAccessTime =Long.parseLong(cookie.getValue());
                Date date = new Date(lastAccessTime);
                out.write(date.toLocaleString());
            }
        }
    }else {
        out.write("这是您第一次访问本站!");
    }
    
    //用户访问过之后重新设置用户的访问时间,存储到cookie中,然后发送到客户端浏览器
    Cookie cookie = new Cookie("lastAccessTime", System.currentTimeMillis()+"");//创建一个cookie,cookie的名字是lastAccessTime
    //将cookie对象添加到response对象中,这样服务器在输出response对象中的内容时就会把cookie也输出到客户端浏览器
    response.addCookie(cookie);
    

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

    doGet(request,response);
    }

}


cuiwei1026522829
cuiwei1026522829   Ds   Rxr 2015.07.11 15:34

就像你说的,报错,应该就是没有拿到cookie吧,应该把报错内容也写出来

Csdn user default icon
上传中...
上传图片
插入图片