Hi
This is interview question ask to me .If we override the service(), doGet() and doPost() method of any servlet which one method is invoke at the execution time of servlet.
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Satyapriya NayakPosted Feb 6, 2012, 1:40 AM
Service() method.
Life cycle methods of a servlet:
init()
service()
destroy()
Init() First the servlet is constructed, then initialized wih the init() method.
This method is called once for a servlet instance. When first time servlet is called, servlet container creates instance of that servlet and loaded into the memory. Future requests will be served by the same instance without creating the new instance. Servlet by default multithreaded application.init() method is used for inilializing servlet variables which are required to be passed from the deployment descriptor web.xml. ServletConfig is passed as the parameter to init() method which stores all the values configured in the web.xml. It is more convenient way to initialize the servlet.
Service() Then Service() method is called and this is the place where servlet spends most of its life. Each request here comes as a separate thread. This method then internally calls the doGet() or doPost() method depending upon the type of request comes.
Destroy() Then destroy() method is called just before destroying the Servlet. This method should be used if any clean code needs to be run before destroying the servlet.
Example
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletLifeCycleExample extends HttpServlet {
private int count;
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
getServletContext().log("init() called");
count=0;
}
@Override
protected void service(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
getServletContext().log("service() called");
count++;
response.getWriter().write
("Incrementig the count: Count = "+count);
}
@Override
public void destroy() {
getServletContext().log("destroy() called");
}
}
Thanks