您好,登錄后才能下訂單哦!
這篇文章主要介紹如何使用servlet實現統計網頁訪問次數,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
(1)ServletContext和ServletConfig的區別
ServletContext作為整個web應用的共享數據
ServletConfig只是作為當前servlet的數據共享,下一個servlet訪問時,是訪問不到的
將顯示的統計次數顯示在HTML頁面上:
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class countServlet1 */ @WebServlet("/countServlet1") public class countServlet1 extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public countServlet1() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //設置字符編碼 request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html; charset=utf-8"); //獲取全局的共享數據 ServletContext servletContext = this.getServletContext(); //獲取計數器count Integer count = (Integer) servletContext.getAttribute("count"); //如果獲取的計算器對象為空 ,說明是第一次訪問,并將count,放入servletCount if( servletContext.getAttribute("count") == null) { count = 1; servletContext.setAttribute("count", count); }else { //否則就不是第一次訪問,將登陸的計數器進行加1的數據更新 servletContext.setAttribute("count", count+1); } //將登陸的次數顯示在頁面上 PrintWriter out =response.getWriter(); out.print("<!DOCTYPE html>\r\n" + "<html>\r\n" + "<head>\r\n" + "<meta charset=\"UTF-8\">\r\n" + "<title>登陸網頁次數統計</title>\r\n" + "</head>\r\n" + "<body>"); out.print("<h2>"); out.print("您是第 "+ servletContext.getAttribute("count")+"位訪客"); out.print("<h2>"); out.print("</body>\r\n" + "</html> } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
(1)在eclipse中顯示的次數
(2)在火狐中顯示的次數
(3)在360中顯示的次數
以上是“如何使用servlet實現統計網頁訪問次數”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。