美文网首页
javaweb之统计网站访问量小案例

javaweb之统计网站访问量小案例

作者: rainbowz | 来源:发表于2019-03-28 13:08 被阅读0次

    效果图

    图片.png

    项目目录:


    图片.png 图片.png

    切换浏览器,数据连续累加(全局作用域,服务器不重启,数据会一直保留)

    html代码

        <h3>hello world!</h3>
        <a href="WebCount">click1</a>
    

    CountServlet代码

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            
            request.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Type ","text/html;charset=UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            
            
        
            response.getWriter().append("Served at: ").append(request.getContextPath());
            PrintWriter out= response.getWriter();
            out.print("hello world!");
            
            
            ServletContext  context =this.getServletContext();
            Integer count=(Integer) context.getAttribute("counter");
            if(count==null) {
                count=1;
                context.setAttribute("counter", count+1);
            }
            
            request.getServletContext().setAttribute("counter",count+1);
            response.getWriter().println("网站访问量为:"+count);  
            
        /*  response.setContentType("text/html");
            response.setCharacterEncoding("UTF-8");
            
            out.println("<!DOCTYPE html>" + 
                    "<html>");
            out.println("<HEAD><TITLE>count times</TITLE></HEAD>");
            
            out.println("<BODY>");
            out.println("<h3><font color='skyblue'>");
            out.println("you are num:"+context.getAttribute("counter"));
            out.println("</font><h2>");
            out.println("</BODY>");
            out.println("</HTML>");*/
            
            out.flush();
            out.close();
            
        
            
            /*int totalCount=1;
            //默认访问量为1
            
            Object count = request.getServletContext().getAttribute("Faker");
               //判断count是否为null,不为null表示曾经访问过,直接将count赋值给totalCount
            
            if(count!=null) {
                totalCount=(int)count;
            }
            
            //访问次数累加
                    request.getServletContext().setAttribute("Faker",totalCount+1);
                    response.getWriter().println("网站访问量为:"+totalCount); 
                    
                    
            //输出到界面
    */      
        }
    

    参考:https://blog.csdn.net/qq_42813491/article/details/87807132

    相关文章

      网友评论

          本文标题:javaweb之统计网站访问量小案例

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