随笔都是学习笔记
随笔仅供参考,为避免笔记中可能出现的错误误导他人,请勿转载。
posts - 398,comments - 0,views - 13万

思路:

1、首先设置一个变量记录访问次数初值为1(打开即访问);

2、判断ServletContext对象中的count属性是否为空;

  空:在ServletContext对象中添加一个新的count属性值,并赋初值为1;
  非空:获取ServletContext对象中的count属性值,将count加1,再将count赋值给ServletContext对象;

复制代码
package cn.webpro.ml;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 统计访问数量
 * @author CDU_LM
 *
 */
@WebServlet("/AServlet")
public class AServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取ServletContext对象
        ServletContext app = this.getServletContext();
        // 定义一个变量记录访问次数,初始值为1,因为不管count是否存在,打开网页就已经访问了一次
        int count = 1;
        // 判断是否访问次数为空
        if(app.getAttribute("count") != null){    // 不为空
            count = (int)app.getAttribute("count");    // 获取访问次数
            count += 1;    // 访问次数加一
            app.setAttribute("count", count);    // 设置加1后的访问次数
        }else {    // 访问次数为空
            app.setAttribute("count", 1);    // 设置访问次数的属性和值,初始值为1
        }
        // 响应次数
        response.getWriter().print(count);
        System.out.println(count);    // 打印访问次数
    }
}
复制代码

浏览器请求结果:

控制台输出结果:

 

posted on   时间完全不够用啊  阅读(292)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示