首页 > 代码库 > Servlet学习的两个案例之网站访问次数的统计
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); }}
注:我是初学者,发表博客只是学习笔记,欢迎探讨指教,希望可以结实良师益友。
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。