网站访问量统计案例
源码:
AServlet.java
1 package one.servlet; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 6 import javax.servlet.ServletContext; 7 import javax.servlet.ServletException; 8 import javax.servlet.http.HttpServlet; 9 import javax.servlet.http.HttpServletRequest; 10 import javax.servlet.http.HttpServletResponse; 11 12 public class AServlet extends HttpServlet { 13 14 public void doGet(HttpServletRequest request, HttpServletResponse response) 15 throws ServletException, IOException { 16 ServletContext context=this.getServletContext(); 17 Integer count = (Integer)context.getAttribute("count"); 18 if(count==null){ 19 context.setAttribute("count", 1); 20 }else{ 21 context.setAttribute("count", count+1); 22 } 23 count = (Integer)context.getAttribute("count");//重新获取count的值 24 //向浏览器输出,用到响应对象! 25 PrintWriter pw=response.getWriter(); 26 pw.print("<h1>requested count:"+count+"</h1>");//把这个数字输出到浏览器 27 } 28 }
BServlet.java
1 package one.servlet; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 6 import javax.servlet.ServletContext; 7 import javax.servlet.ServletException; 8 import javax.servlet.http.HttpServlet; 9 import javax.servlet.http.HttpServletRequest; 10 import javax.servlet.http.HttpServletResponse; 11 12 public class BServlet extends HttpServlet { 13 14 public void doGet(HttpServletRequest request, HttpServletResponse response) 15 throws ServletException, IOException { 16 ServletContext context=this.getServletContext(); 17 Integer count = (Integer)context.getAttribute("count"); 18 if(count==null){ 19 context.setAttribute("count", 1); 20 }else{ 21 context.setAttribute("count", count+1); 22 } 23 count = (Integer)context.getAttribute("count");//重新获取count的值 24 //向浏览器输出,用到响应对象! 25 PrintWriter pw=response.getWriter();//流 26 pw.print("<h1>requested count:"+count+"</h1>");//把这个数字输出到浏览器 27 } 28 }
不管是访问AServlet还是BServlet ,都会统计它们被请求的次数;如果关掉Tomcat(服务器),计数就会随ServletContext而死亡。
版权声明:本文为xjs1874704478原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。