看了马士兵老师的视频,感觉有一点点理解~~
ServletContext对象相当于保存于服务器端的一块静态内存块,对于相同浏览器、相同web application都可以访问该对象的内容,直到服务器关闭后该内存块会被清空。
参考http://www.cnitblog.com/gavinkin555/articles/32860.html (可能理解的存在错误,有错的请指正~~谢谢。)
虽然看上去可以用作统计用户访问网页的次数,但由于可能存在服务器被关闭或者浏览器不同,无法保证统计的一致性,故建议使用将统计次数存入数据库中。
接下来是马老师的例子实现代码,有些地方可能不一样:
TestServletContext.java
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 {
response.setContentType("text/html;charset=gb2312");
PrintWriter pw=response.getWriter();
pw.println("<html><head><title>Session追踪</title></head><body bgcolor='#FDF5E6'>");
ServletContext context=this.getServletContext();
Integer accessCount=(Integer)context.getAttribute("accessCount");
if(accessCount==null)
{
accessCount=new Integer(0);
}
pw.println("<h1>"+accessCount+"</h1>");
context.setAttribute("accessCount", accessCount+1);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}
web.xml
<servlet>
<servlet-name>TestServletContext</servlet-name>
<servlet-class>TestServletContext</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestServletContext</servlet-name>
<url-pattern>/TestServletContext</url-pattern>
</servlet-mapping>