美文网首页
Java: 网站访问统计代码

Java: 网站访问统计代码

作者: 梦之志 | 来源:发表于2018-09-17 22:31 被阅读0次
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        /*
         * 1. 获取ServletContext对象
         * 2. 从ServletContext对象中获取名为count的属性
         *   3. 如果存在:给访问量加1,然后再保存回去;
         *   4. 如果不存在:说明是第一次访问,向Servletcontext中保存名为count的属性,值为1
         */
        ServletContext app = this.getServletContext();
        Integer count = (Integer)app.getAttribute("count");
        if(count == null) {
            app.setAttribute("count", 1);
        } else {
            app.setAttribute("count", count+1);
        }
        
        /*
         * 向浏览器输出
         *   需要使用响应对象!
         */
        PrintWriter pw = response.getWriter();
        pw.print("<h1>" + count + "</h1>");
    }
}

相关文章

网友评论

      本文标题:Java: 网站访问统计代码

      本文链接:https://www.haomeiwen.com/subject/qekjnftx.html