如何在 Servlet 中不声明其类的对象的情况下调用 getServletContext
在 servlet 中,如何在不声明其类的对象的情况下调用 getServletContext? getServletContext 在其声明中没有 static 。考虑一个例子 - ServletContext context=getServletContext();
In servlets, how does getServletContext get called without declaring an object of its class? getServletContext does not have static in its declaration. Consider for an example- ServletContext context=getServletContext();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
tl;dr
您编写的 Servlet 从其超类
HttpServlet
继承了getServletContext
方法,而后者又从其超类GenericServlet
继承了该方法。您编写的 servlet 类的对象会由您的 Web 容器(例如 Apache Tomcat)自动实例化, Eclipse Jetty 等。请参阅 Servlet 生命周期。
您的 Servlet ➜
HttpServlet
➜GenericServlet
代码:
... 的缩写:
this
是对运行该代码的任何对象的引用。在我们的例子中,该对象是您自己的 servlet。运行时的 servlet 是您在开发时编写的类的实例,由 Web 容器自动实例化。该类(您编写的类)是
HttpServlet
。该超类HttpServlet
从其超类GenericServlet
。该 GenericServlet 类携带方法
getServletContext
。子类HttpServlet
继承该方法。您自己的类(作为 HttpServlet 的子类)也继承该方法。我怎么知道这一切?通过阅读 Javadoc。
请参阅 Jakarta Servlet 规范页面。
tl;dr
The Servlet you wrote inherits the
getServletContext
method from its superclassHttpServlet
, which in turn inherits the method from its superclassGenericServlet
.An object of the servlet class you write is automatically instantiated by your web container such as Apache Tomcat, Eclipse Jetty, etc. See Servlet Life Cycle in the Servlet specification.
Your Servlet ➜
HttpServlet
➜GenericServlet
The code:
… is short for:
The
this
is a reference to whatever object is running that code. In our case here, that object is your own servlet.Your servlet at runtime is an instance of the class you wrote at development time, automatically instantiated by your web container. That class, the class you authored, is a subclass of
HttpServlet
. That superclassHttpServlet
extends from its superclassGenericServlet
.That
GenericServlet
class carries the methodgetServletContext
. The subclassHttpServlet
inherits that method. And so too does your own class, as a subclass ofHttpServlet
, inherit that method.How do I know all this? By reading the Javadoc.
See the Jakarta Servlet specification page.