小弟在学习servlet application时遇到的一个问题,下面是实现客户端访问了servlet多少次的部分代码:
import javax.servlet.http.*;public class TestServletContext extends HttpServlet{
protected void doGet(HttpServletRequest req,HttpServletResponse resp)
            throws ServletException,java.io.IOException{ PrintWriter out = response.getWrite(); ServletContext application = this.getServletContext(); Integer accessCount = (Integer)application.getAttribute("accessCount"); ...... }
}对于这句Integer accessCount = (Integer)application.getAttribute("accessCount");有点不懂,
application是ServletContext类型,但是ServletContext 是个接口类型,我查api文档,这个类没有具体的实现类,
如何能调用getAttribute方法呢??请高手帮忙解释下!!小弟谢谢了。。

解决方案 »

  1.   

    因为你:
      ServletContext application = this.getServletContext();
    所得到的 application 是 ServletContext 的实现类,并不是接口本身。有点类似于:HashMap 和 Map 之间的关系。你可以 System.out.println(application.getClass()); 看看输出就知道了。
      

  2.   


    你很牛,谢谢你了。。我试了一下,查了一些资料,这涉及tomcat内部实现的问题,现在弄清楚了。。