當你在網上發(fā)表了一邊文章,在希望更多的人能看到你寫的文章,同時也想能夠查看準確的訪問人數,每看到那訪問人數的數字跳動,無疑會有一種成就感。本篇文章將會帶你如何用 Java 代碼來實現 Servlet 統(tǒng)計頁面訪問次數的功能。
實現思路:
1.新建一個CallServlet類繼承HttpServlet,重寫doGet()和doPost()方法;
2.在doPost方法中調用doGet()方法,在doGet()方法中實現統(tǒng)計網站被訪問次數的功能,用戶每請求一次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("頁面訪問統(tǒng)計");
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);
}
}
前端展示結果:
以上就是基于 Servlet 實現統(tǒng)計頁面訪問次數功能的全部內容,想要了解更多相關 Java 的內容,請繼續(xù)關注W3Cschool,也希望大家多多支持。