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