servlet实现统计网页访问次数

一、基础知识

  • (1)ServletContext和ServletConfig的区别
    • ServletContext作为整个web应用的共享数据
    • ServletConfig只是作为当前servlet的数据共享,下一个servlet访问时,是访问不到的

二、代码实现

  • 将显示的统计次数显示在HTML页面上:

import java.io.IOException;
import java.io.PrintWriter;

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;

/**
 * Servlet implementation class countServlet1
 */
@WebServlet("/countServlet1")
public class countServlet1 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public countServlet1() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//设置字符编码
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		
		
		
		//获取全局的共享数据
		ServletContext servletContext = this.getServletContext();
		
		//获取计数器count
		Integer count = (Integer) servletContext.getAttribute("count");
		
		//如果获取的计算器对象为空 ,说明是第一次访问,并将count,放入servletCount
		if( servletContext.getAttribute("count") == null) {
			count = 1;
			servletContext.setAttribute("count", count);
		}else {
			//否则就不是第一次访问,将登陆的计数器进行加1的数据更新
			servletContext.setAttribute("count", count+1);
		}
		
		//将登陆的次数显示在页面上
		PrintWriter out =response.getWriter();
		out.print("\r\n" + 
				  "\r\n" + 
				  "\r\n" + 
				  "\r\n" + 
				  "登陆网页次数统计\r\n" + 
				  "\r\n" + 
				  "");
		out.print("

"); out.print("您是第 "+ servletContext.getAttribute("count")+"位访客"); out.print("

"); out.print("\r\n" + ""); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }

三、在不同浏览器显示的次数

  • (1)在eclipse中显示的次数
    servlet实现统计网页访问次数_第1张图片
  • (2)在火狐中显示的次数
    servlet实现统计网页访问次数_第2张图片
  • (3)在360中显示的次数
    servlet实现统计网页访问次数_第3张图片

你可能感兴趣的:(JAVA,Web)