The Three Big Lifecycle Moments
1 init() | When it’s called The Container calls init() on the servlet instance after the servlet instance is created but before the servlet can service any client requests. | What it’s for Gives you a chance to initialize your servlet before handling any client requests. | Do you override it? Possibly. If you have initialization code (like getting a database connection or registering yourself with other objects), then you’ll override the init() method in your servlet class. |
2 service() | When it’s called When the first client request comes in, the Container starts a new thread or allocates a thread from the pool, and causes the servlet’s service() method to be invoked. | What it’s for This method looks at the request, determines the HTTP method (GET, POST, etc.) and invokes the matching doGet(), doPost(), etc. on the servlet. | Do you override it? No. Very unlikely. You should NOT override the service() method. Your job is to override the doGet() and/or doPost() methods and let the service() implementation from HTTPServlet worry about calling the right one. |
3 doGet() and/or doPost() | When it’s called The service() method invokes doGet() or doPost() based on the HTTP method (GET, POST, etc.) from the request. (We’re including only doGet() and doPost() here, because those two are probably the only ones you’ll ever use.) | What it’s for This is where your code begins! This is the method that’s responsible for whatever the heck your web app is supposed to be DOING. You can call ... |