Servlet實現統計頁面訪問次數功能

本文實例為大傢分享瞭Servlet實現統計頁面訪問次數的具體代碼,供大傢參考,具體內容如下

實現思路:

1.新建一個CallServlet類繼承HttpServlet,重寫doGet()和doPost()方法;

2.在doPost方法中調用doGet()方法,在doGet()方法中實現統計網站被訪問次數的功能,用戶每請求一次servlet,使得訪問次數times加1;

3.獲取ServletContext,通過它的功能記住上一次訪問後的次數。

在web.xml中進行路由配置:

<!-- 頁面訪問次數 -->
  <servlet>
    <servlet-name>call</servlet-name>
    //CallServlet為處理前後端交互的後端類
    <servlet-class>CallServlet</servlet-class>  
  </servlet>
  <servlet-mapping>
    <servlet-name>call</servlet-name>
    <url-pattern>/call</url-pattern>
</servlet-mapping>

CallServlet類:

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created with IntelliJ IDEA
 * Details about unstoppable_t:
 * User: Administrator
 * Date: 2021-04-07
 * Time: 14:57
 */

//獲得網站被訪問的次數
public class CallServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        ServletContext context = getServletContext();
        Integer times = (Integer) context.getAttribute("times");
        if (times == null) {
            times = new Integer(1);
        } else {
            times = new Integer(times.intValue() + 1);
        }
        PrintWriter out= resp.getWriter();
        out.println("<html><head><title>");
        out.println("頁面訪問統計");
        out.println("</title></head><body>");
        out.println("當前頁面被訪問瞭");
        out.println("<font color=red size=20>"+times+"</font>次");
        context.setAttribute("times",times);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}

前端展示結果:

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。