What happens behind the scene when Web Application is deployed in Web Server like Tomcat?
- 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
Lifecycle of ServletContext
ServletContextlives for as long as the web app lives. It is shared among all requests in all sessions.