对cookies读写简单的例子

本文介绍了一个使用Java Servlet实现的简单Cookie计数器示例。该示例通过设置和读取名为“CookieCount”的Cookie来跟踪用户在10秒内的访问次数。如果在指定时间内用户未访问,则会创建新的Cookie并设置初始计数值为1。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.davic.working.testing;

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

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jboss.system.server.ServerConfig;

public class CookieCounter extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;

public void init(ServletConfig config) throws ServletException {
super.init(config);
}

@Override
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
boolean cookieFound = false;
Cookie thisCookie = null;
response.setContentType("text/html;charset=gb2312;");
PrintWriter out = response.getWriter();

Cookie[] cookies = request.getCookies();
System.out.println("length:" + cookies.length);
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
thisCookie = cookies[0];
if (thisCookie.getName().equals("CookieCount")) {
cookieFound = true;
break;
}
}
}

if (cookieFound == false) {
thisCookie = new Cookie("CookieCount", "1");
thisCookie.setMaxAge(10);
response.addCookie(thisCookie);
}

if (cookieFound) {
int cookieCount = Integer.parseInt(thisCookie.getValue());
cookieCount++;
thisCookie.setMaxAge(10);
thisCookie.setValue(String.valueOf(cookieCount));
response.addCookie(thisCookie);
out.println("<p>这是您在近" + 10
* (Integer.parseInt(thisCookie.getValue()) - 1) + "秒内登陆"
+ thisCookie.getValue() + "次系统");
} else {
out.println("<p>" + "你10内都没有登陆进系统");
}
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值