欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Servlet实现页面访问量统计实例

程序员文章站 2024-03-19 22:40:28
...

    我们知道一个Web应用程序只有一个ServletContext对象,而且该对象可以被Web应用程序中所有Servlet所访问。因此使用ServletContext对象来保存一些需要在Web应用程序*享的信息再合适不过了。

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;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "CounterServlet",
        urlPatterns = "/counterServlet")
public class CounterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        Integer count = null;

        //为避免线程安全问题,使用synchronized关键字进行同步
        synchronized (context){
            count = (Integer) context.getAttribute("counter");
            if(count == null){
                count = new Integer(1);
            }else {
                count = new Integer(count.intValue() + 1);
            }
            context.setAttribute("counter",count);
        }

        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.print("<html><head>");
        out.print("<title>页面访问统计</title>");
        out.print("</html><body>");
        out.println("<h2>页面已被访问了</h2>" + "<b>"+count+"</b>" +"次");
        out.println("</body></html>");
    }
}

 

相关标签: 实例