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

效果图

图片.png

项目目录:


图片.png
图片.png

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

html代码

    

hello world!

click1

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("" + 
                "");
        out.println("count times");
        
        out.println("");
        out.println("

"); out.println("you are num:"+context.getAttribute("counter")); out.println("

"); out.println(""); out.println("");*/ 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之统计网站访问量小案例)