本文转自:http://linweihan.iteye.com/blog/125777
作者:上帝也犯困
下面是Servlet实现访问次数的例子
//ShowTimesServlet.java /*Servlet实现访问次数的例子!*/ import java.io.*; import java.util.zip.*; import javax.servlet.*; import javax.servlet.http.*; /* 这个类实现访问次数。显示访问次数!看是第几次访问! */ public class ShowTimesServlet extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, java.io.IOException { response.setContentType("text/html"); HttpSession session = request.getSession(); String heading; Integer accessCount =(Integer)session.getAttribute("accessCount"); if(accessCount == null) { accessCount = new Integer(0); heading = "Welcom,You are first time to visit!"; } else { heading = "Welcome Backer"; accessCount = new Integer(accessCount.intValue()+1); } session.setAttribute("accessCount",accessCount); PrintWriter out = response.getWriter(); out.println("The title:"+heading); out.println("Access count: "+accessCount); } public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, java.io.IOException { doGet(request,response); } }
下面是通过servleContext来做访问次数
package org.linweihan.test; 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 TestServletContext extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext servletContext = this.getServletContext(); Integer accessCount =(Integer)servletContext.getAttribute("accessCount"); if(accessCount == null){ accessCount = 0; }else{ accessCount = accessCount + 1; } servletContext.setAttribute("accessCount", accessCount); PrintWriter out = response.getWriter(); out.println("<html><body><h2>"+accessCount+"</body></html>"); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
区别在于session是局部的,servletContext是共享的.
当换了另一个窗口开始访问又从0开始计数,而servletContext则是接下去计数.