cookie小试刀—编写servlet利用Cookie保存上次访问该servlet的时间

简单分析,由于http协议的无状态性不能保存数据,我们利用cookie保存用户上次登陆该servlet的时间,第一次登陆告诉是第一次登陆还没记录,(servlet中获取到的cookie值为空说明是第一次登陆这时设置上cookie的值保存这次登陆的时间)第二次及以后则显示上次的登陆时间(servlet中获取到的cookie值不为空,将cookie中的值显示即上次登录的时间)。

代码:

package com.zc.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import java.util.Calendar;
import java.util.GregorianCalendar;

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 TestCookie2 extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Constructor of the object.
	 */
	public TestCookie2() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request,response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		
		
		/*获取上册登陆的时间*/
		GregorianCalendar gc=new GregorianCalendar();
		
		String time=gc.get(Calendar.YEAR)+"-"+gc.get(Calendar.MONTH)+"-"+gc.get(Calendar.DATE)+"-"+gc.get(Calendar.HOUR)+":"+gc.get(Calendar.MINUTE)+":"+gc.get(Calendar.SECOND);//存放系统获取的时间
		if(gc.get(Calendar.AM_PM)==1){//判断上次登陆是上午还是下午
			time+="  PM";
		}else{
			time+="  AM";
		}
		
		Cookie timeCookie = new Cookie("lastTime",time);//存放上次登录时间的cookie
		timeCookie.setMaxAge(3600*24*365);//设置cookie的有效时间是一年
		
		response.addCookie(timeCookie);//添加时间cookie
		
		Cookie[] Cookies = request.getCookies();//获取所有cookie
		String lastTime=null;//存放上次登陆的时间
		for(int i=0;Cookies!=null&&i<Cookies.length;i++){
			if("lastTime".equals(Cookies[i].getName())){
				lastTime=Cookies[i].getValue();
				break;
			}
		}
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		if(lastTime==null){
			out.println("您是第一次登陆");
		}else{
			out.println("上次登陆的时间是:"+lastTime);
		}
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}

从上面的试验中可以看出cookie保存的总是上一次访问该网站时的信息。



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为您解答这个问题。 在JSP页面,可以通过Cookie对象来记录和获取上次访问时间。 下面是一个示例代码: ``` <% // 获取当前时间 Date currentDate = new Date(); // 获取上次访问时间Cookie Cookie lastVisitCookie = null; Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals("lastVisit")) { lastVisitCookie = cookie; break; } } } // 设置新的Cookie String lastVisitTime = "首次访问"; if (lastVisitCookie != null) { lastVisitTime = lastVisitCookie.getValue(); } Cookie newVisitCookie = new Cookie("lastVisit", currentDate.toString()); newVisitCookie.setMaxAge(60*60*24*30); // 设置Cookie的有效期为30天 response.addCookie(newVisitCookie); %> 您上次访问本站的时间是:<%= lastVisitTime %> ``` 在上面的代码,我们首先获取了当前时间,并通过`request.getCookies()`方法获取到了上次访问时间Cookie。如果没有找到该Cookie,则说明是用户首次访问,将上次访问时间设置为“首次访问”。 接着,我们创建了一个新的Cookie对象,并通过`response.addCookie()`方法将其添加到响应。需要注意的是,我们通过`setMaxAge()`方法设置Cookie的有效期为30天,这样用户下次访问时也能够获取到上次访问时间。 最后,我们通过JSP的表达式语言输出了上次访问时间。 希望这个示例能够帮到您,如果您有任何疑问,请随时问我。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值