Servlet学习的两个案例之网站访问次数的统计
一、统计次数的Servlet源码
package com.shanrengo; import java.io.IOException; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 用戶訪問countServlet,訪問次數+1 * 1.在countServlet初始化的時候,向ServletContext中保存一個訪問次數0 * @author Administrator * */ public class CountServlet extends HttpServlet { @Override public void init() throws ServletException { // TODO Auto-generated method stub //向ServletContext保存訪問次數0 //ServletContext 中setAttribute方法 //1.獲得servletContext對象 ServletContext context = getServletContext(); //2.保存數據 context.setAttribute("visitTimes", 0); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //每次訪問都會執行doGet //1.從servletContext中獲得visitTimes ServletContext context = getServletContext(); int times = (Integer) context.getAttribute("visitTimes"); //2.將visitTimes++ times++; //3.更新 context.setAttribute("visitTimes", times); System.out.println("網站被訪問了一次!"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
二、显示统计次数的servlet源码
package com.shanrengo; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class CountShowServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext context = getServletContext(); int times = (Integer) context.getAttribute("visitTimes"); response.getWriter().println(times); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
注:我是初学者,发表博客只是学习笔记,欢迎探讨指教,希望可以结实良师益友。
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。