Servlets play the role of a helper app in the web server. It is preferred because of performance where server has to launch a heavy-weight process for each and every request for that resource.
- Servlets should be deployed to Web Container (Servlet Container e.g. Tomcat)
Web Container (Servlet Container)
- Responsible for managing the lifecycle of servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access rights
- There is single instance of Servlet per JVM instance. The classes are loaded and servlet object is created during container boot up which lives during the whole JVM lifecycle
- init method is called by container to initialize servlet instance. ServletConfig can be passed to customize servlet at run time. init method can be used to costly operations e.g. create JDBC connection or anything that need to be performed one time.
- For every request, container creates new HTTPServletRequest/HTTPServletResponse (in case of HTTPServlet) and every request do have separate thread
- service method is responsible for calling doGet/doPost methods (HTTPServlet)
- destroy method is called when servlet object is destroyed
- Servlet API contained in the Java package hierarchy javax.servlet
- The package javax.servlet.http defines HTTP-specific subclasses of the generic servlet elements