當(dāng)你在網(wǎng)上發(fā)表了一邊文章,在希望更多的人能看到你寫的文章,同時也想能夠查看準(zhǔn)確的訪問人數(shù),每看到那訪問人數(shù)的數(shù)字跳動,無疑會有一種成就感。本篇文章將會帶你如何用 Java 代碼來實(shí)現(xiàn) Servlet 統(tǒng)計(jì)頁面訪問次數(shù)的功能。
實(shí)現(xiàn)思路:
1.新建一個CallServlet類繼承HttpServlet,重寫doGet()和doPost()方法;
2.在doPost方法中調(diào)用doGet()方法,在doGet()方法中實(shí)現(xiàn)統(tǒng)計(jì)網(wǎng)站被訪問次數(shù)的功能,用戶每請求一次servlet,使得訪問次數(shù)times加1;
3.獲取ServletContext,通過它的功能記住上一次訪問后的次數(shù)。
在web.xml中進(jìn)行路由配置:
<!-- 頁面訪問次數(shù) -->
<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
*/
//獲得網(wǎng)站被訪問的次數(shù)
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)計(jì)");
out.println("</title></head><body>");
out.println("當(dāng)前頁面被訪問了");
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);
}
}
前端展示結(jié)果:
以上就是基于 Servlet 實(shí)現(xiàn)統(tǒng)計(jì)頁面訪問次數(shù)功能的全部內(nèi)容,想要了解更多相關(guān) Java 的內(nèi)容,請繼續(xù)關(guān)注W3Cschool,也希望大家多多支持。