Java Web显示用户上次访问时间(实例一)

                **利用Cookie技术实现显示用户上次访问的功能** 

import java.io.IOException;
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 LastAccessServlet  extends HttpServlet{
  
	private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
          //指定服务器输出内容的编码方式为utf-8,防止乱码
           resp.setContentType("text/html;charset=utf-8");
            String lastaccesstime=null;
           //获取所有cookie,并将这些cookie存放在数组中
            Cookie[]  cookies=req.getCookies();
             //遍历获取cookie数组
               for (int i = 0;cookies!=null&& i < cookies.length;) {
				    lastaccesstime=cookies[i].getValue();
				    break;
			}
         //判断是否存在名为lastaccesstime的cookie值
        if(lastaccesstime==null) {
	    resp.getWriter().println("您是首次访问本站!!");
       }else { 
	    resp.getWriter().println("您上次访问的时间是:"+lastaccesstime);
	    }
	     //获取cookie信息并将当前时间作为cookie值发送给客户端
        String currenttime= new SimpleDateFormat("yyyy-MM-dd-hh:mm:ss").format(new Date());
        Cookie cookie=new Cookie("lastaccess",currenttime);
        resp.addCookie(cookie);
  }
    @Override
    	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 
    		this.doGet(req, resp);
    	}
}

web.xml配置文件

       
     LastAccessServlet 
     LastAccessServlet
     
 
 
       LastAccessServlet
       /LastAccessServlet
    
 
    

你可能感兴趣的:(JavaWeb之小例子)