Home > OS >  how does getServletContext get called without declaring an object of its class in Servlets
how does getServletContext get called without declaring an object of its class in Servlets

Time:04-07

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();

CodePudding user response:

tl;dr

The Servlet you wrote inherits the getServletContext method from its superclass HttpServlet, 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 ➜ HttpServletGenericServlet

The code:

ServletContext context = getServletContext() ;

… is short for:

ServletContext context = this.getServletContext() ;

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 superclass HttpServlet extends from its superclass GenericServlet.

That GenericServlet class carries the method getServletContext. The subclass HttpServlet inherits that method. And so too does your own class, as a subclass of HttpServlet, inherit that method.

How do I know all this? By reading the Javadoc.

See the Jakarta Servlet specification page.

  • Related