显示用户上次访问时间


使用Servlet实现获取Cookie信息并将当前时间作为Cookie作为值发给客户端。

package com.wangkai.test;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
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 Dourem extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        String lastAccess = null;
        Cookie[] cookies = request.getCookies();
        for(int i=0;i<cookies.length && cookies!=null;i++){
            if("lastAccess".equals(cookies[i].getName())){
                lastAccess=cookies[i].getValue();
                break;
            }
        }
        if(lastAccess==null)
        {
            out.println("你是首次访问");
        }else{
            out.println("你上次访问的时间是:"+lastAccess);
        }
        String nowTime=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
        Cookie cookie = new Cookie("lastAccess",nowTime);
        response.addCookie(cookie);
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doGet(request,response);
    }
}

声明:子客|版权所有,违者必究|如未注明,均为原创|网站采用BY-NC-SA协议授权

转载:请注明原文链接 - 显示用户上次访问时间


Carpe Diem and Do what I like