Use Servlet to Realize the Function of Counting the Number of Visited Websites

Ideas:

1. Create a new Servlet class that inherits HttpServlet and rewrite the doGet() and doPost() methods;
2. Call the doGet() method in the doPost method, and implement the function of counting the number of times the website has been visited in the doGet() method. A servlet increases the number of visits times by 1;
3. Get the ServletContext, and remember the number of visits after the last visit through its function.

Implementation code:

package readPath;

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

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class test001 extends HttpServlet {
    
    
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
		
	 response.setContentType("text/html;charset=GB2312");
	 //设置编码,不然中文会变成乱码
	 ServletContext context = this.getServletContext();
	 PrintWriter out = response.getWriter();
	 Integer times =(Integer)context.getAttribute("times");
	 if(times==null) {
    
    
		 times = new Integer(1);
	 }else {
    
    
		 times = new Integer(times.intValue()+1);
	 }
	 out.println("<html><head><title>");
	 out.println("页面访问统计~");
	 out.println("</title></head><body>");
	 out.println("当前页面被访问过了");
	 out.println("<font color=red size=20>"+times+"</font>次");
	 //设置属性,将times保存到当前的上下文中
	 context.setAttribute("times", times);
	 
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
		// TODO Auto-generated method stub
		this.doGet(req, resp);
	}

}

operation result:

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_43553142/article/details/105691356