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

ServletContext
  • 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.
Workflow
  • 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.
load-on-startup
  • 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

<servlet>
	<servlet-name>resteasy-servlet</servlet-name>
	<servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
</servlet>

Spring implementation

<servlet>
	<servlet-name>mvc-dispatcher</servlet-name>
	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	<load-on-startup>1</load-on-startup>
</servlet>
Lifecycle of ServletContext
  • The ServletContext lives for as long as the web app lives. It is shared among all requests in all sessions.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.