您的位置:首页 > 其它

通过Cookie统计用户访问网页的次数

2008-08-29 20:42 1151 查看
1 package lesson3_2.cookie;
2
3 import javax.servlet.*;
4 import javax.servlet.http.*;
5 import java.io.*;
6 import java.util.*;
7
8 public class CookieServlet extends HttpServlet {
9 private static final String CONTENT_TYPE = "text/html; charset=GBK";
10
11 //Initialize global variables
12 public void init() throws ServletException {
13 }
14
15 //Process the HTTP Get request
16 public void doGet(HttpServletRequest request, HttpServletResponse response) throws
17 ServletException, IOException {
18 response.setContentType(CONTENT_TYPE);
19 PrintWriter out = response.getWriter();
20
21 // 获得Cookie
22 Cookie cookies[] = request.getCookies();
23 // 声明一个Cookie的引用
24 Cookie myCookie = null;
25 // 如果有Cookie的话,就进入循环
26 if (cookies != null) {
27 for (int i = 0; i < cookies.length; i++) {
28 // 如果找到所要查找的Cookie,就把这个Cookie保存下来,然后跳出循环
29 if (cookies[i].getName().equals("count")) {
30
31 myCookie = cookies[i];
32 break;
33 }
34 }
35 }
36 // 如果有这个Cookie
37 if (myCookie != null) {
38 // 定义一个存放次数的变量
39 int count = 0;
40 // 通过getValue()方法得到从客户端myCookie的值,得到的值是一个String类型的要将转换成int类型的,才能进行计数操作
41 count = Integer.parseInt(myCookie.getValue());
42 // 累加访问的次数
43 count++;
44 // 把count的值添加到定义的Cookie对象中
45 myCookie.setValue(String.valueOf(count));
46 // 设置Cookie的最大保存时间
47 myCookie.setMaxAge(60 * 60 * 24 * 30);
48 // 把Cookie添加到客户端
49 response.addCookie(myCookie);
50 // 输出
51 out.print("您这是第" + count + "次访问");
52 // out.print("您这是第" + myCookie.getValue() + "次访问");
53
54 } else {
55 // 如果客户端是第一次访问该页面,也就是没有Cookie,就要先实例化一个Cookie对象
56 Cookie cookie = new Cookie("count", "1");
57 // 设置Cookie的最大保存时间
58 cookie.setMaxAge(60 * 60 * 24 * 30);
59 // 把Cookie添加到客户端
60 response.addCookie(cookie);
61 // 输出
62 out.print("您这是第1次访问");
63 }
64
65 }
66
67 //Process the HTTP Post request
68 public void doPost(HttpServletRequest request, HttpServletResponse response) throws
69 ServletException, IOException {
70 doGet(request, response);
71 }
72
73 //Clean up resources
74 public void destroy() {
75 }
76 }
77
78
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: