What happens behind the scene when Web Application is deployed in Web Server like Tomcat?

  • It provides a set of methods that a servlet uses to communicate with its servlet container.
  • There is one context per “web application” per Java Virtual Machine.
  • A “web application” is a collection of servlets and content installed under a specific subset of the server’s URL namespace such as /catalog and possibly installed via a .war file.
  • When a web application is loaded, the servlet container creates the ServletContext once and keeps it in the server’s memory.
  • The web app’s web.xml file is parsed, and each <servlet>, <filter> and <listener> found  or each class annotated with @WebServlet, @WebFilter and @WebListener respectively is  instantiated once and kept in the server’s memory as well.
  • When a Servlet has a <servlet><load-on-startup> or @WebServlet(loadOnStartup) value greater than 0, its init() method is also invoked during startup with a new ServletConfig.
  • Those servlets are initialized in the same order specified by that value (1, 2, 3…).
  • If the same value is specified for more than one servlet, then each of those servlets is loaded in the order they appear in the web.xml or @WebServlet classloading.
  • In the event the “load-on-startup” value is absent, the init() method will be invoked whenever the HTTP request hits that servlet for the very first time.
Some Servlet Implementation code from web.xml

RestEasy implementation for Jboss


Spring implementation

Lifecycle of ServletContext
  • The ServletContext lives for as long as the web app lives. It is shared among all requests in all sessions.

1 Comment

simon · December 6, 2019 at 10:38 pm

Very useful and interesting. Thankyou for sharing this Great article

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *