小白第一次学习Cookie技术

Cookie技术

Cookie

Cookie可以通过javax.servlet.http.Cookie类的构造方法Cookie(String name,String value)创建,示例代码如下:
Cookie vistendcCountC=new Cookie(“vistedCount”,“1000”);
其中第一个参数name用于指定Cookie的属性名,第二个参数value用于指定属性值。
#下面是运行结果:
在这里插入图片描述Alt

下面是代码:
package servlet;//servlet类必须有包名
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/CookieTest")//"/CookieTest"为url={"/CookieTest"}
public class CookieTest extends HttpServlet {//servletl类必须继承javax.servlet.http.HttpServlet类
private static final long serialVersionUID = 1L;//定义程序序列化baiID。
//序列化ID等同于身份验证,主要用于程序的版本控制,维护不同版本的兼容性以及避免在程序版本升级时程序报告的错误。

protected void doGet(HttpServletRequest request, HttpServletResponse response) 
		throws ServletException, IOException {
	response.setContentType("text/html;charset=UTF-8");
	PrintWriter out = response.getWriter();
	//时间不能有空格,不然后续Cookie创建后
	//运行报错( An invalid character [32] was present in the Cookie value)。
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");
	String nowTime = sdf.format(new Date());
	String lastVistTime = "";//访问时间
	int vistedCount = 0;//访问次数
	//获取客户端浏览器保存的所有Cookie
	Cookie[] myCookies = request.getCookies();
	if(myCookies != null) {
		for (Cookie cookie : myCookies) {
			//判断是否为最近访问过的Cookie,Cookie中属性名为lastVist,属性值为上次访问的时间
			if("lastVist".equals(cookie.getName())) {
				lastVistTime = cookie.getValue();
			}
			//判断是否为记录访问次数的Cookie,Cookie中属性名为vistedCount,属性值为上次访问的次数
			if("vistedCount".equals(cookie.getName())) {
				vistedCount = Integer.valueOf(cookie.getValue());
			}
		}
	}
	//不是第一次访问,输出上次访问时间
	if(!"".equals(lastVistTime)){
		out.println("您上次访问时间为:" + lastVistTime);
	}
	//输出访问次数
	out.println("您是第:" + (vistedCount + 1) + "访问该网站。");
	//以本次访问时间创建同名Cookie
	Cookie lastVistTimeC = new Cookie("lastVist", nowTime);
	//设置最大存活时间为一年
	lastVistTimeC.setMaxAge(365 * 24 * 60 * 60);
	//以访问次数创建同名Cookie
	Cookie vistedCountC = new Cookie("vistedCount", (vistedCount + 1) + "");
	//设置最大存活时间为一年
	vistedCountC.setMaxAge(365 * 24 * 60 * 60);
	//将两个Cookie对象响应到客户端
	response.addCookie(lastVistTimeC);
	response.addCookie(vistedCountC);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	doGet(request, response);
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值